import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Database from '@ioc:Adonis/Lucid/Database';
import KeyValue from 'App/Models/KeyValue';
import LogDetectFile from 'App/Models/LogDetectFile';
import axios from 'axios';

export default class LogsController {
  public async showLog({request, response}: HttpContextContract) {
    try {
      // fghf
      console.log(request.params().name);
      let fileDetect = await LogDetectFile.findBy(
        "file_name",
        request.params().name
      );
      let logsDetect = await Database.rawQuery(
        "select * from log_reports where id_file = " + fileDetect?.id_ldf
      );
  
      let modelSpecialDetected = [];
      let issueSpecialDetected = [];
      let listLine = logsDetect[0]
        .map((obj) => obj.line)
        .filter((value, index, self) => {
          return self.indexOf(value) === index;
        })
        .sort((a, b) => a - b);
  
      const content = await axios.get(
        request.params().name.search("AUTO") !== -1
          ? "http://192.168.5.7:8080/AUTOlog/" + request.params().name
          : "http://192.168.5.7:8080/" + request.params().name
      );
      let allValue = await KeyValue.all();
      let listKeyValues = allValue.filter(
        (i) =>
          i.$original.key === "MODEL_SPECIAL" ||
          i.$original.key === "CATCH_FAULTY"
      );
  
      let MODEL_SPECIAL = allValue
        .filter((i) => i.$original.key === "MODEL_SPECIAL")
        .map((obj) => obj.$original.value);
  
      let listExcludeErr = allValue
        .filter((i) => i.$original.key === "EXCLUDE_ERR")
        .map((obj) => obj.$original.value);
  
      let data = content.data.split("\n");
      data.map((line, index) => {
        data[index] = index + 1 + "|-|" + line;
        listKeyValues
          .map((obj) => obj.$original.value)
          .map(async (value) => {
            if (
              line.search(value) !== -1 &&
              listExcludeErr.filter((err) => line.includes(err)).length === 0
            ) {
              data[index] =
                data[index].slice(0, data[index].search(value)) +
                "|-|" +
                value +
                "|-|" +
                data[index].slice(data[index].search(value) + value.length);
              // }
            }
          });
      });
  
      listLine.map((u) => {
        if (
          listExcludeErr.filter((err) => data[u - 1].includes(err)).length === 0
        ) {
          if (MODEL_SPECIAL.filter((i) => data[u - 1].includes(i)).length > 0) {
            modelSpecialDetected.push(data[u - 1]);
          } else {
            issueSpecialDetected.push(data[u - 1]);
          }
        }
      });
      let modelSpecial =
        modelSpecialDetected.length > 0 ? modelSpecialDetected.join("\n") : "";
      let issueItem =
        issueSpecialDetected.length > 0 ? issueSpecialDetected.join("\n") : "";
      response.status(200).send({
        modelSpecial: modelSpecial,
        issueItem: issueItem,
        contentFile: data.join("\n"),
      });
    } catch (error) {
      // console.error(error);
      response.status(203).send("FILE NOT FOUND");
    }
  }

  public async getAllLogDetect({request, response}: HttpContextContract) {
    try {
      let fileDetect = await LogDetectFile.all();
      let listFiles = fileDetect.map((obj) => obj.file_name);
      response.status(200).send(listFiles);
    } catch (error) {
      response.status(203).send("NO FILE");
    }
  }

  public async store({}: HttpContextContract) {}

  public async show({}: HttpContextContract) {}

  public async edit({}: HttpContextContract) {}

  public async update({}: HttpContextContract) {}

  public async destroy({}: HttpContextContract) {}
}
