import Env from "@ioc:Adonis/Core/Env";
// const axios = require("axios");
// import fs from "fs";

import axios from "axios";
import { addLogFunction } from "./addLogFunction";
import moment from "moment";

export const checkIndexSN = async (content, beginLine, nameF) => {
  try {
    const arrayLine = content;

    let output = [];
    if (arrayLine !== undefined) {
      for (let i = 0; i < arrayLine.length; i++) {
        let SN = arrayLine[i]
          ?.split("SN:")[1]
          ?.trim()
          .replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
        if (
          arrayLine[i].search("PID:") !== -1 &&
          arrayLine[i].search("SN:") !== -1 &&
          arrayLine[i].search("%") === -1 &&
          arrayLine[i]
            ?.split(",")[2]
            ?.split(":")[1]
            ?.replace("\r", "")
            .trim() !== "" &&
          SN !== "N/A" &&
          SN.length > 4 &&
          i >= beginLine
        ) {
          if (output.some((u) => u.SN === SN)) {
            output.map((u, index) => {
              if (u.SN === SN) {
                output[index].PID =
                  arrayLine[i]?.split("VID:")[0] !== undefined
                    ? arrayLine[i]
                        ?.split("VID:")[0]
                        ?.slice(arrayLine[i]?.split("VID:")[0]?.search("PID"))
                        ?.split(":")[1]
                        ?.split(",")[0]
                        ?.trim()
                    : "";
                (output[index].VID =
                  arrayLine[i]?.split("SN:")[0] !== undefined
                    ? arrayLine[i]
                        ?.split("SN:")[0]
                        ?.split("VID:")[1]
                        ?.split(",")[0]
                        ?.trim()
                    : ""),
                  (output[index].line = output[index].line.concat([i + 1]));
              }
            });
          } else {
            output.push({
              PID:
                arrayLine[i]?.split("VID:")[0] !== undefined
                  ? arrayLine[i]
                      ?.split("VID:")[0]
                      ?.slice(arrayLine[i]?.split("VID:")[0]?.search("PID"))
                      ?.split(":")[1]
                      ?.split(",")[0]
                      ?.trim()
                  : "",
              VID:
                arrayLine[i]?.split("SN:")[0] !== undefined
                  ? arrayLine[i]
                      ?.split("SN:")[0]
                      ?.split("VID:")[1]
                      ?.split(",")[0]
                      ?.trim()
                  : "",
              SN:
                arrayLine[i].split("SN:")[1] !== undefined
                  ? SN.search(" ") !== -1
                    ? SN?.split(" ")[0]
                    : SN
                  : "",
              line: [i + 1],
              fileName: nameF,
              warehouse:
                (nameF.search("-US") !== -1 ||
                  nameF.search(".US") !== -1 ||
                  nameF.search("US-") !== -1) &&
                nameF.search("AUS") === -1
                  ? "US"
                  : "AU",
            });
          }
        }

        if (arrayLine[i].search("Serial Number") !== -1 && i >= beginLine) {
          let PCB_SN = arrayLine[i]
            ?.split("Serial Number")[1]
            .split(":")[1]
            ?.replace("\r", "")
            .trim()
            .replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
          if (
            //Neu SN da nam trong output
            output.some((u) => u.SN === PCB_SN)
          ) {
            output.map((u, index) => {
              if (u.SN === PCB_SN) {
                output[index].line = output[index].line.concat([i + 1]);
              }
            });
          } else {
            // if (
            //   /^[A-Z0-9-]{5,}$/.test(
            //     PCB_SN
            //   )
            // ) {

            output.push({
              PID: "",
              VID: "",
              SN: PCB_SN?.search(" ") !== -1 ? PCB_SN?.split(" ")[0] : PCB_SN,
              line: [i + 1],
              fileName: nameF,
              warehouse:
                (nameF.search("-US") !== -1 ||
                  nameF.search(".US") !== -1 ||
                  nameF.search("US-") !== -1) &&
                nameF.search("AUS") === -1
                  ? "US"
                  : "AU",
            });
            // }
          }
        }

        if (
          arrayLine[i].search("Processor board ID") !== -1 &&
          i >= beginLine
        ) {
          let PBID = arrayLine[i]
            ?.split(" ")
            [arrayLine[i]?.split(" ").length - 1]?.replace("\r", "")
            .trim()
            .replace(/[!@#$%^&*()_+{}\[\]:;<>,.?~\\/]/g, "");
          if (
            //Neu SN da nam trong output
            output.some((u) => u.SN === PBID)
          ) {
            output.map((u, index) => {
              if (u.SN === PBID) {
                output[index].line = output[index].line.concat([i + 1]);
              }
            });
          } else {
            if (PBID?.length >= 8) {
              output.push({
                PID: "",
                VID: "",
                SN: PBID?.search(" ") !== -1 ? PBID?.split(" ")[0] : PBID,
                line: [i + 1],
                fileName: nameF,
                warehouse:
                  (nameF.search("-US") !== -1 ||
                    nameF.search(".US") !== -1 ||
                    nameF.search("US-") !== -1) &&
                  nameF.search("AUS") === -1
                    ? "US"
                    : "AU",
              });
            }
          }
        }
      }
      //   console.log(nameF+" output\n", output);
      if (output.filter((i) => i.PID !== "").length > 0) {
        let token =
          "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwaS5uc3d0ZWFtLm5ldC9hcGkvbG9naW4iLCJpYXQiOjE2ODkzOTEyMDMsImV4cCI6MTcyMDkyNzIwMywibmJmIjoxNjg5MzkxMjAzLCJqdGkiOiJreFA1MW9jck5rdEYzSzY3Iiwic3ViIjozNjkwLCJwcnYiOiJjOGVlMWZjODllNzc1ZWM0YzczODY2N2U1YmUxN2E1OTBiNmQ0MGZjIn0.p-aE0oWkKmdrcKWD94oSmMd_CMbY_4MoqADIwYIhIKw";

        let token_int =
          "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2ludC5pcHN1cHBseS5jb20uYXUvYXBpL2xvZ2luIiwiaWF0IjoxNjg5ODYyNjAxLCJleHAiOjE3MjEzOTg2MDEsIm5iZiI6MTY4OTg2MjYwMSwianRpIjoiUElZVjNBM3ZPQVlMQ081SyIsInN1YiI6MSwicHJ2IjoiYzhlZTFmYzg5ZTc3NWVjNGM3Mzg2NjdlNWJlMTdhNTkwYjZkNDBmYyJ9.UcybIKMBjTAY9i0PfIDQMtqHyN72Ul0jC03ZDGLGpMI";

        let data = {
          data: output.filter((i) => i.PID !== ""),
          urlAPI: "/api/test-log-serial-number/save-data",
        };

        const response = await axios.post(
          "https://api.nswteam.net/api/transferPostData",
          data,
          { headers: { Authorization: "Bearer " + token } }
        );

        if (Env.get("RUN_ENV") === "prod") {
          const response_int = await axios.post(
            "https://int.ipsupply.com.au/api/transferPostData",
            data,
            { headers: { Authorization: "Bearer " + token_int } }
          );

          console.log(nameF + " response\n", response_int.data);
          const fileName =
            "./app/store/logsAPI/" +
            moment(Date.now()).format("DD_MM_YYYY").toString() +
            ".log";
          addLogFunction(fileName, "URL: https://int.ipsupply.com.au/api/transferPostData\n"+ JSON.stringify(response_int.data, null, 2), "Update SN index to int.ipsupply.com.au");
        }
      }
    }
  } catch (error) {
    console.log("Can't connect to log server", error);
  }
};
