const express = require("express");
const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");
const router = express.Router();
const clientService = require("../services/clientService");
const globalService = require("../services/globalService");
const userService = require("../services/userService");
const logger = require("../utils/logger");

router.get("/read/:numClient", async (req, res) => {
  const numClient = req.params.numClient;
  const idClient = await globalService.getRecordIdFromFieldValue("client", "numClient", numClient);

  if (idClient) {
    res.json({ valid: true, idClient });
  } else {
    res.json({ valid: false });
  }
});

router.get("/read/id/:idClient", async (req, res) => {
    const idClient = req.params.idClient;

    try {
      const client = await clientService.getClient(idClient);
  
      res.json({ valid: Boolean(client), client });
    } catch (error) {
      logger.log('error', `Error fetching client with ID ${idClient}:`, error);
      res.status(500).json({ valid: false, error: "Internal Server Error" });
    }
  });

router.post("/create", async (req, res) => {
  const client = await clientService.createClient();

  res.json({ valid: Boolean(client), client });
});

router.post("/extract", async (req, res) => {
  const data = req.body;
  const user = await userService.getUserByMatricule(data.matricule);
  const filePath = path.join("public", "vbs", "script_cl063", "config", "client_" + user.matriculeIT + ".txt");

  fs.writeFile(filePath, "numClient:" + data.numClient, (err) => {
    if (err) {
      logger.log('error', `Unable to write file: ${err}`);
      res.status(500).json({ error: "Unable to write file" });
     
      return;
    }
  });

  exec("wscript.exe public\\vbs\\script_cl063\\extract.vbs", async (err) => {
    if (err) {
      logger.log('error', `Error executing VBS script: ${err}`);
      res.status(500).json({ error: "Error executing VBS script" });
      
      return;
    }

    let retries = 0;
    const maxRetries = 10;
    const retryInterval = 1000; // En millisecondes

    // Attente que le fichier .txt soit complété
    while (retries < maxRetries) {
      const extractedData = fs.readFileSync(filePath, "utf8");
      const lines = extractedData.split("\n");
      const initialJson = {};

      for (const line of lines) {
        const [key, value] = line.split(":");
        
        if (key && value) {
          const trimmedKey = key.trim();
          const trimmedValue = value.trim();
          initialJson[trimmedKey] = trimmedValue;
        }
      }

      if (initialJson.nomClient) {
        // Traitement du JSON
        const cleanedJson = {
          adresseAgent: globalService.cleanDoubleSpaces(initialJson.adresseAgent),
          adresseClient: globalService.cleanDoubleSpaces(initialJson.adresseClient),
          codePostal: globalService.cleanDoubleSpaces(initialJson.codePostal),
          faxAgent: globalService.cleanDoubleSpaces(initialJson.faxAgent).replace(/\s/g, ""),
          nomAgent: globalService.cleanDoubleSpaces(initialJson.nomAgent),
          nomClient: globalService.cleanDoubleSpaces(initialJson.nomClient),
          numAgent: globalService.cleanDoubleSpaces(initialJson.numAgent),
          numClient: globalService.cleanDoubleSpaces(initialJson.numClient),
          siren: globalService.cleanDoubleSpaces(initialJson.siren),
          telAgent: globalService.cleanDoubleSpaces(initialJson.telAgent).replace(/\s/g, ""),
        };

        // Extraction du code postal et de la ville pour l'agent
        const agentAddressMatch = cleanedJson.adresseAgent.match(/(\d+)\s+(.+) (\d{5}) (.+)/);
        
        if (agentAddressMatch) {
          cleanedJson.adresseAgent = agentAddressMatch[1] + " " + agentAddressMatch[2];
          cleanedJson.postalAgent = agentAddressMatch[3];
          cleanedJson.villeAgent = agentAddressMatch[4];
        }

        // Extraction du code postal et de la ville pour le client
        const clientAddressMatch = cleanedJson.codePostal.match(/(\d{5})\s+(.+)/);
        
        if (clientAddressMatch) {
          cleanedJson.postalClient = clientAddressMatch[1];
          cleanedJson.villeClient = clientAddressMatch[2];
        }

        // Suppression de la propriété codePostal maintenant que nous l'avons séparée
        delete cleanedJson.codePostal;

        res.json({ valid: true, data: cleanedJson });
        return;
      }

      logger.log("warn", `Tentative ${retries + 1}/${maxRetries} de récupération des données collectées sur AxAPAC`);
      
      await new Promise((resolve) => setTimeout(resolve, retryInterval));
      retries++;
    }

    logger.log('error', `Erreur dans l'extraction AxAPAC`);
    
    res.status(500).json({ error: "Timeout waiting for the file to be completed" });
  });
});

router.post("/update/:idClient", async (req, res) => {
  const idClient = req.params.idClient;
  const data = req.body;
  const record = await globalService.updateRecordFromData("client", idClient, data);

  res.json({ valid: Boolean(record) });
});

module.exports = router;
