import { Request, Response } from "express";
import { getWbot, removeWbot } from "../libs/wbot";
import { removeDir } from "../helpers/DeleteDirectory";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { StartWhatsAppSession } from "../services/WbotServices/StartWhatsAppSession";
import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppService";

import { restartWhatsSession } from "../helpers/RestartWhatsSession";

import path from 'path';
import { getIO } from "../libs/socket";
import { stat } from "fs";

import { setRestoreControll, getRestoreControll, shifRestoreControll } from "../helpers/RestoreControll";

import autoRestore from "../helpers/AutoRestore";
import axios from "axios";
import Whatsapp from "../models/Whatsapp";
import endPointQuery from "../helpers/EndPointQuery";


// let lstRestore: any = [] 

const store = async (req: Request, res: Response): Promise<Response> => {
  const { whatsappId } = req.params;
  const whatsapp = await ShowWhatsAppService(whatsappId);

  StartWhatsAppSession(whatsapp);

  return res.status(200).json({ message: "Starting session." });
};

const update = async (req: Request, res: Response): Promise<Response> => {
  const { whatsappId } = req.params;

  const { whatsapp } = await UpdateWhatsAppService({
    whatsappId,
    whatsappData: { session: "" }
  });

  StartWhatsAppSession(whatsapp);

  return res.status(200).json({ message: "Starting session." });
};





const restart = async (req: Request, res: Response): Promise<Response> => {

  const { whatsappId } = req.params;

  const io = getIO();

  if (Object.keys(req.body).length > 0) {

    let lstRestore: any = getRestoreControll()

    for (let i = 0; i < lstRestore.length; i++) {

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

    }

    return res.status(200).json({});

  }

  let whatsapp: any = await Whatsapp.findByPk(whatsappId)

  if (whatsapp) {

    await whatsapp.update({ status: 'OPENING' });

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

    whatsapp = JSON.parse(JSON.stringify(whatsapp))

    console.log('whatsapp url: ', whatsapp.url)

    await endPointQuery(`${whatsapp.url}/api/restore`, {})
  }



  autoRestore(whatsappId)

  return res.status(200).json({ message: "Starting session." });
};



const remove = async (req: Request, res: Response): Promise<Response> => {

  const { whatsappId } = req.params;

  // const whatsapp = await ShowWhatsAppService(whatsappId);

  // const wbot = getWbot(whatsapp.id);

  // await wbot.logout();

  try {

    const wbot_url = await getWbot(whatsappId);

    let response = await axios.post(`${wbot_url}/api/disconnect`);


  } catch (error) {

    console.log('There was an error on try disconnect the whatsapp id: ', whatsappId)

  }




  return res.status(200).json({ message: "Session disconnected." });
};

export default { store, remove, update, restart };
