package LoginDb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OtpUtility {

    static String endpoint1 = "https://api.digilexa.in/v1/verify";
    static String endpoint2 = "https://api.digilexa.in/v1/verify/validate";

    public String sendOtp(String user, String pacsId, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        //connects to dB and fetch apiKey, configId, phone number

        StringBuffer response = null;
        String verifyId = "";
        String phoneNumber = "";
        String apiKey = "";
        String configId = "";

        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = DbHandler.getDBConnection();
            statement = connection.createStatement();
          //  rs = statement.executeQuery("select ld.MOBILE_NO, md.CONFIG_ID, md.API_KEY from LOGIN_DETAILS ld JOIN USER_MFA_DETAILS md ON ld.PACS_ID = md.pacs_id where ld.PACS_ID='" + pacsId + "' and ld.LOGIN_ID='" + user + "'");
            //System.out.println("query executed successfully to fetch mob nom, api key etc.");
            while (rs.next()) {
                phoneNumber = rs.getString("MOBILE_NO");
                configId = rs.getString("CONFIG_ID");
                apiKey = rs.getString("API_KEY");
                //System.out.println("phone numnber is: " + phoneNumber + "configId is: " + configId + "apiKkey is: " + apiKey);
            }

        } catch (SQLException ee) {
            //ee.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
                rs.close();
            } catch (SQLException ee) {
                //System.out.println("Error Occurred during connection close.");
            } catch (NullPointerException npe) {
                //
            }
        }

        try {
            URL url = new URL(endpoint1);
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.setRequestMethod("POST");
            urlconnection.setRequestProperty("Content-Type", "application/json");
            urlconnection.setRequestProperty("apikey", apiKey);
            urlconnection.setDoOutput(true);

            String requestBody = "{\"configId\": \"" + configId + "\", \"to\": \"" + phoneNumber + "\"}";
            //System.out.println("-------------------------check------------------------------");
            OutputStream os = urlconnection.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();
            //System.out.println("-------------------------check------------------------------");
            int responseCode = urlconnection.getResponseCode();
            //System.out.println("Response Code: " + responseCode);

            BufferedReader br = null;
            if (responseCode == 200) {
              //  br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
            }else{
                br = new BufferedReader(new InputStreamReader(urlconnection.getErrorStream()));
            }
            String inputLine;
            response = new StringBuffer();

           // while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();

            //System.out.println("Response Body: " + response.toString());
        } catch (MalformedURLException mu) {
            mu.printStackTrace();
            req.setAttribute("error", "Error in otp genertion.");
            req.getRequestDispatcher("/Login.jsp").forward(req, res);
            req.getSession().invalidate();
        } catch (IOException ie) {
            ie.printStackTrace();
            req.setAttribute("error", "Error in otp genertion.");
            req.getRequestDispatcher("/Login.jsp").forward(req, res);
            req.getSession().invalidate();
        }

        try {
            String responseString = response.toString();
            JSONObject jsonResponse = new JSONObject(responseString); // Parse the response string into a JSON object
            verifyId = jsonResponse.getString("verifyId");// Extract the verifyId field
            //System.out.println("Verify ID: " + verifyId);

        } catch (JSONException je) {
            //je.printStackTrace();
        }
        return verifyId;
        //return "this is demo verify id";
    }

    public String verifyValidateOtp(String verifyId, String otp, String user, String pacsId) {
        StringBuffer response = null;
        String message = null;
        String apiKey = "";
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = DbHandler.getDBConnection();
            statement = connection.createStatement();
           // rs = statement.executeQuery("select API_KEY from USER_MFA_DETAILS where PACS_ID='" + pacsId + "'");
            //System.out.println("query executed successfully fetch otp");
            while (rs.next()) {
                apiKey = rs.getString("API_KEY");
                //System.out.println("while verifying the api key is---------- " + apiKey);
            }

        } catch (SQLException ee) {
            //ee.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
                rs.close();
            } catch (SQLException ee) {
                //System.out.println("Error Occurred during connection close.");
            }
        }

        try {
            URL url = new URL(endpoint2);
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.setRequestMethod("POST");
            urlconnection.setRequestProperty("Content-Type", "application/json");
            urlconnection.setRequestProperty("apikey", apiKey);
            urlconnection.setDoOutput(true);
            //System.out.println("otp entered from the screen isn :--------- " + otp);
            String requestBody = "{\"verifyId\": \"" + verifyId + "\", \"otp\": \"" + otp + "\"}";

            OutputStream os = urlconnection.getOutputStream();
            os.write(requestBody.getBytes());
            os.flush();

            int responseCode = urlconnection.getResponseCode();
            //System.out.println("Response Code duing verification is-------- : " + responseCode);
            BufferedReader br = null;

            if (responseCode == 200) {
              //  br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
            } else//example 401 or 500
            {
                br = new BufferedReader(new InputStreamReader(urlconnection.getErrorStream()));
            }

            String inputLine;
            response = new StringBuffer();

           // while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();

            //System.out.println("Response Body: " + response.toString());
        } catch (MalformedURLException mu) {
            //mu.printStackTrace();
        } catch (IOException ie) {
            //ie.printStackTrace();
        }
        try {
            String responseString = response.toString();
            JSONObject jsonResponse = new JSONObject(responseString); // Parse the response string into a JSON object
            message = jsonResponse.getString("message");// Extract the verifyId field
            //System.out.println("message: " + message);

        } catch (JSONException je) {
            //je.printStackTrace();
        }
        //System.out.println("message after verfication is:------" + message);
        return message;

        //return "OTP Verified Successfully!";
    }

}
