import { intervalToDuration } from "date-fns";
import { del, get, set } from "./RedisClient";
import { getIO } from "../libs/socket";
import controllByNumber from "./controllByNumber";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";

let timer: any;

const AutoRemoteTickets = async () => {
  try {
    let obj: any = await controllByNumber();

    if (!obj?.tickets) return;

    // console.log("remote tickets: ", obj?.tickets);

    for (const ticket of obj.tickets) {
      if (!ticket.includes("open") || ticket.includes("messageDateTime"))
        continue;

      const regex = /"updatedAt":"([^"]+)"/;
      let match = ticket.match(regex);

      const updatedAt = match ? match[1] : null;

      console.log("updatedAt: ", updatedAt);

      let timeDiff: any = intervalToDuration({
        start: new Date(updatedAt),
        end: new Date()
      });

      console.log("----------> idle time timeDiff: ", timeDiff);

      if (timeDiff.minutes > 2) {
        match = ticket.match(/"id":(\d+)/);
        let ticketId = match ? match[1] : null;
        console.log("ticketId: ", ticketId);

        ticketId = JSON.parse(ticketId);

        let ticketRemote = await get({
          key: `remote:ticketId:${ticketId}`
        });

        if (ticketRemote) {
          ticketRemote = JSON.parse(ticketRemote);

          ticketRemote = {
            ...ticketRemote,
            ...{ status: "pending" }
          };

          set(`remote:ticketId:${ticketId}`, JSON.stringify(ticketRemote));

          await UpdateTicketService({
            ticketData: {
              status: "pending",
              userId: null
            },
            ticketId
          });

          const io = getIO();
          io.emit("remoteTickesControllIdleOpen", {
            action: "update",
            ticketId
          });
        }
      }
    }

    for (const ticket of obj.tickets) {
      if (!ticket.includes("messageDateTime")) continue;

      let match = ticket.match(/"messageDateTime":("[^"]*")/);
      let messageDateTime = match ? match[1] : null;
      console.log("messageDateTime: ", messageDateTime);

      match = ticket.match(/"whatsappId":(\d+)/);
      let whatsappId = match ? match[1] : null;
      console.log("whatsappId: ", whatsappId);

      const whatsapp = await get({
        key: `whatsapp:${whatsappId}`
      });

      match = whatsapp.match(/"number":"(\d+)"/);
      let number = match ? match[1] : null;
      console.log("number: ", number);

      match = ticket.match(/"id":(\d+)/);
      let ticketId = match ? match[1] : null;
      console.log("ticketId: ", ticketId);

      number = JSON.parse(number);
      ticketId = JSON.parse(ticketId);

      let timeDiff: any = intervalToDuration({
        start: new Date(JSON.parse(messageDateTime)),
        end: new Date()
      });

      console.log("______timeDiff: ", timeDiff);

      if (timeDiff.seconds > 50) {
        del(`remote:ticketId:${ticketId}`);

        obj = await controllByNumber();

        const io = getIO();
        io.emit("remoteTickesControll", {
          action: "update",
          tickets: obj.ticketIds
        });
      }
    }
  } catch (error) {
    console.log("There was an error on auto remote tickets service: ", error);
  }
};

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

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

timer = setInterval(schedule, 5000);

export default schedule;
