package com.axelor.apps.hr.web;

import com.axelor.apps.hr.db.Granding;
import com.axelor.apps.hr.db.repo.GrandingRepository;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GrandingController {

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

  public void testGrandingConnection(ActionRequest request, ActionResponse response) {

    Long grandingId = (Long) request.getContext().asType(Granding.class).getId();
    Granding granding = Beans.get(GrandingRepository.class).find(grandingId);

    String ipAdress = granding.getIpAdress();
    String code = granding.getCode().toString();

    try {

      String[] args = {
        "python",
        "C:\\Users\\administrator\\Desktop\\attendance\\main.py",
        "--commande",
        "ping",
        "--ip_address",
        ipAdress,
        "--code",
        code
      };

      Process p = Runtime.getRuntime().exec(args);

      // Capture the output stream (standard output)
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        log.info("Python script (Granding ping) output: " + line);
      }

      // Capture the error stream (standard error)
      BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = errorReader.readLine()) != null) {
        log.error("Python script (Granding ping) error: " + line);
      }

      // Wait for the process to complete and check the exit value
      int exitCode = p.waitFor();

      // Check if the process ran successfully
      if (exitCode == 0) {
        log.info("Python script executed successfully (Granding ping).");
        response.setFlash("Connection successful.");
      } else {
        log.error("Python script execution (Granding ping) failed with exit code: " + exitCode);
        response.setFlash("Connection failed.");
      }

    } catch (IOException e) {
      // Check if the file is not found based on the message or error code
      if (e.getMessage().contains("The system cannot find the file specified")) {
        log.error("Python script file (Granding ping) not found: " + e.getMessage());
      } else {
        log.error("An error occurred while executing the Python script (Granding ping).", e);
      }
      response.setFlash("Connection failed.");
      TraceBackService.trace(e);
    } catch (InterruptedException e) {
      // Handle any interruption errors
      response.setFlash("Connection failed.");
      log.error("Python script (Granding ping) execution interrupted.", e);
      Thread.currentThread().interrupt();
    }
  }
}
