import SettingTicket from "../models/SettingTicket";
import ListTicketTimeLife from "../services/TicketServices/ListTicketTimeLife";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import BotIsOnQueue from "./BotIsOnQueue";

import {
  format as _format,
  isWithinInterval,
  parse,
  subMinutes
} from "date-fns";

import ptBR from "date-fns/locale/pt-BR";
import { splitDateTime } from "./SplitDateTime";
import Whatsapp from "../models/Whatsapp";

const fsPromises = require("fs/promises");
const fs = require("fs");

let timer: any;

const AutoCloseTickets = async () => {
  try {
    // const botInfo = await BotIsOnQueue('botqueue')

    // if (!botInfo.userIdBot) return

    const whatsapps = await Whatsapp.findAll({ group: ["number"] });

    for (const whatsapp of whatsapps) {
      // console.log("-------> whatsapp: ", JSON.stringify(whatsapps, null, 6));

      const ticketExpiration = await SettingTicket.findOne({
        where: { key: "ticketExpiration", number: whatsapp.number }
      });

      if (ticketExpiration && ticketExpiration.value == "enabled") {
        const startTime = splitDateTime(
          new Date(
            _format(
              new Date(ticketExpiration.startTime),
              "yyyy-MM-dd HH:mm:ss",
              {
                locale: ptBR
              }
            )
          )
        );

        const seconds = timeStringToSeconds(startTime.fullTime);  

        let tickets: any = await ListTicketTimeLife({
          timeseconds: seconds,
          status: "open",
          number: whatsapp.number
        }); 

        for (let i = 0; i < tickets.length; i++) {
          await UpdateTicketService({
            ticketData: { status: "closed", statusChatEnd: "FINALIZADO" },
            ticketId: tickets[i].ticket_id,
            msg: ticketExpiration.message
          });
        }
      }
    }
  } catch (error) {
    console.log("There was an error on try close the bot tickets: ", error);
  }
};

function timeStringToSeconds(timeString: any) {
  const [hours, minutes, seconds] = timeString.split(":").map(Number);
  return hours * 3600 + minutes * 60 + seconds;
}

const schedule = async () => {
  try {
    clearInterval(timer);

    await AutoCloseTickets();
  } catch (error) {
    console.log("error on schedule: ", error);
  } finally {
    timer = setInterval(schedule, 60000);
  }
};

timer = setInterval(schedule, 60000);

export default schedule;
