package com.axelor.apps.hr.web;

import com.axelor.app.AppSettings;
import com.axelor.apps.base.web.AppBaseController;
import com.axelor.apps.hr.service.AuthorizationService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wslite.json.JSONArray;
import wslite.json.JSONException;
import wslite.json.JSONObject;

@Singleton
public class AuthorizationController {

  private final AppSettings appSettings = AppSettings.get();
  private final String BASE_URL = appSettings.get("portail.api.baseurl");

  private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  public void fetchAuthorization(ActionRequest request, ActionResponse response) {
    try {

      String accessToken = AppBaseController.getAccessToken();
      if (accessToken == null) {
        logger.error("Access token is null, unable to proceed.");
        return;
      }

      String jsonResponse = fetchAA(accessToken);

      if (jsonResponse != null) {
        try {
          JSONArray jsonArray = new JSONArray(jsonResponse);

          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Beans.get(AuthorizationService.class).saveAA(jsonObject);
          }

          // Reload the response after successfully saving extra hours
          response.setReload(true);

        } catch (JSONException e) {
          // Log the specific JSON parsing error
          System.err.println("Failed to parse JSON: " + jsonResponse);
          e.printStackTrace();
        }
      } else {
        System.err.println("No response received from fetchAA.");
      }
    } catch (Exception e) {
      // General catch for unexpected exceptions
      System.err.println(
          "An error occurred while fetching Authorization Absence: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public void fetchEntryAuthorization(ActionRequest request, ActionResponse response) {
    try {
      String accessToken = AppBaseController.getAccessToken();
      if (accessToken == null) {
        logger.error("Access token is null, unable to proceed.");
        return;
      }
      String jsonResponse = fetchAE(accessToken);

      if (jsonResponse != null) {
        try {
          JSONArray jsonArray = new JSONArray(jsonResponse);

          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Beans.get(AuthorizationService.class).saveAE(jsonObject);
          }

          // Reload the response after successfully saving extra hours
          response.setReload(true);

        } catch (JSONException e) {
          // Log the specific JSON parsing error
          System.err.println("Failed to parse JSON: " + jsonResponse);
          e.printStackTrace();
        }
      } else {
        System.err.println("No response received from fetchAE.");
      }
    } catch (Exception e) {
      // General catch for unexpected exceptions
      System.err.println("An error occurred while fetching Entry Authorization: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public void fetchExitAuthorization(ActionRequest request, ActionResponse response) {
    try {
      String accessToken = AppBaseController.getAccessToken();
      if (accessToken == null) {
        logger.error("Access token is null, unable to proceed.");
        return;
      }
      String jsonResponse = fetchBS(accessToken);

      if (jsonResponse != null) {
        try {
          JSONArray jsonArray = new JSONArray(jsonResponse);

          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Beans.get(AuthorizationService.class).saveBS(jsonObject);
          }

          // Reload the response after successfully saving extra hours
          response.setReload(true);

        } catch (JSONException e) {
          // Log the specific JSON parsing error
          System.err.println("Failed to parse JSON: " + jsonResponse);
          e.printStackTrace();
        }
      } else {
        System.err.println("No response received from fetchBS.");
      }
    } catch (Exception e) {
      // General catch for unexpected exceptions
      System.err.println("An error occurred while fetching Entry Authorization: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public void fetchSalaryAuthorization(ActionRequest request, ActionResponse response) {
    try {
      String accessToken = AppBaseController.getAccessToken();
      if (accessToken == null) {
        logger.error("Access token is null, unable to proceed.");
        return;
      }
      String jsonResponse = fetchAP(accessToken);

      if (jsonResponse != null) {
        try {
          JSONArray jsonArray = new JSONArray(jsonResponse);

          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Beans.get(AuthorizationService.class).saveAP(jsonObject);
          }

          // Reload the response after successfully saving extra hours
          response.setReload(true);

        } catch (JSONException e) {
          // Log the specific JSON parsing error
          System.err.println("Failed to parse JSON: " + jsonResponse);
          e.printStackTrace();
        }
      } else {
        System.err.println("No response received from fetchAP.");
      }
    } catch (Exception e) {
      // General catch for unexpected exceptions
      System.err.println(
          "An error occurred while fetching Salary Authorization: " + e.getMessage());
      e.printStackTrace();
    }
  }

  public String fetchAA(String accessToken) {
    String endpoint = BASE_URL + "tickets/aa/";
    HttpURLConnection conn = null;

    try {
      URL url = new URL(endpoint);
      conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Accept", "application/json");
      // Include the access token in the Authorization header
      conn.setRequestProperty("Authorization", "Bearer " + accessToken);

      int responseCode = conn.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
          StringBuilder response = new StringBuilder();
          String responseLine;
          while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
          }
          // Process the response as needed
          return response.toString();
        }
      } else {
        // Read the error stream for more details
        StringBuilder errorResponse = new StringBuilder();
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
          String errorLine;
          while ((errorLine = br.readLine()) != null) {
            errorResponse.append(errorLine.trim());
          }
        }
        throw new RuntimeException(
            "Failed: HTTP error code: " + responseCode + ", Error: " + errorResponse.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null; // Return null in case of failure
    } finally {
      if (conn != null) {
        conn.disconnect(); // Ensure connection is closed
      }
    }
  }

  public String fetchAE(String accessToken) {
    String endpoint = BASE_URL + "tickets/ae/";
    HttpURLConnection conn = null;

    try {
      URL url = new URL(endpoint);
      conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Accept", "application/json");
      // Include the access token in the Authorization header
      conn.setRequestProperty("Authorization", "Bearer " + accessToken);

      int responseCode = conn.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
          StringBuilder response = new StringBuilder();
          String responseLine;
          while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
          }
          // Process the response as needed
          return response.toString();
        }
      } else {
        // Read the error stream for more details
        StringBuilder errorResponse = new StringBuilder();
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
          String errorLine;
          while ((errorLine = br.readLine()) != null) {
            errorResponse.append(errorLine.trim());
          }
        }
        throw new RuntimeException(
            "Failed: HTTP error code: " + responseCode + ", Error: " + errorResponse.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null; // Return null in case of failure
    } finally {
      if (conn != null) {
        conn.disconnect(); // Ensure connection is closed
      }
    }
  }

  public String fetchBS(String accessToken) {
    String endpoint = BASE_URL + "tickets/bs/";
    HttpURLConnection conn = null;

    try {
      URL url = new URL(endpoint);
      conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Accept", "application/json");
      // Include the access token in the Authorization header
      conn.setRequestProperty("Authorization", "Bearer " + accessToken);

      int responseCode = conn.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
          StringBuilder response = new StringBuilder();
          String responseLine;
          while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
          }
          // Process the response as needed
          return response.toString();
        }
      } else {
        // Read the error stream for more details
        StringBuilder errorResponse = new StringBuilder();
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
          String errorLine;
          while ((errorLine = br.readLine()) != null) {
            errorResponse.append(errorLine.trim());
          }
        }
        throw new RuntimeException(
            "Failed: HTTP error code: " + responseCode + ", Error: " + errorResponse.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null; // Return null in case of failure
    } finally {
      if (conn != null) {
        conn.disconnect(); // Ensure connection is closed
      }
    }
  }

  // Authorisation de paye
  public String fetchAP(String accessToken) {
    String endpoint = BASE_URL + "tickets/ap/";
    HttpURLConnection conn = null;

    try {
      URL url = new URL(endpoint);
      conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Accept", "application/json");
      // Include the access token in the Authorization header
      conn.setRequestProperty("Authorization", "Bearer " + accessToken);

      int responseCode = conn.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
          StringBuilder response = new StringBuilder();
          String responseLine;
          while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
          }
          // Process the response as needed
          return response.toString();
        }
      } else {
        // Read the error stream for more details
        StringBuilder errorResponse = new StringBuilder();
        try (BufferedReader br =
            new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
          String errorLine;
          while ((errorLine = br.readLine()) != null) {
            errorResponse.append(errorLine.trim());
          }
        }
        throw new RuntimeException(
            "Failed: HTTP error code: " + responseCode + ", Error: " + errorResponse.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null; // Return null in case of failure
    } finally {
      if (conn != null) {
        conn.disconnect(); // Ensure connection is closed
      }
    }
  }
}
