import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "./RestartWhatsSession";
import { getRestoreControll, setRestoreControll, shifRestoreControll } from "./RestoreControll";

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

import { getIO } from "../libs/socket";
import path from "path";
import { splitDateTime } from "./SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import { number } from "yargs";

const autoRestore = async (whatsappId: string | number, started_action_by: string = '') => {

    /*const whatsapp = await ShowWhatsAppService(whatsappId);

    // console.log('>>>>>>>>>>> Whatsapp.id: ', whatsappId)

    await restartWhatsSession(whatsapp, true)


    const sourcePath = path.join(__dirname, `../../.wwebjs_auth/sessions/log`)

    if (fs.existsSync(sourcePath)) {

        let log = new Date(new Date() + 'UTC');

        const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))

        let timestamp = Math.floor(Date.now() / 1000)

        let number: any = whatsapp.number

        if (!number) {
            number = ''
        }

        if (started_action_by.trim().length > 0)
            fs.writeFileSync(`${sourcePath}/${timestamp}_restore_${number}_triggered_by_${started_action_by}_id_${whatsappId}.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime}`, (error: any) => { console.log(error) });

    }*/


    setRestoreControll({ 'id': +whatsappId, 'disabled': true })

    let lstRestore: any = getRestoreControll()

    const io = getIO();

    io.emit("whatsappSession", {
        action: "update",
        session: { 'id': +whatsappId, 'disabled': true }
    });

    setTimeout(() => {

        let whatsapp = shifRestoreControll();

        whatsapp.disabled = false

        io.emit("whatsappSession", {
            action: "update",
            session: whatsapp
        });

    }, 25000);

}

export default autoRestore;