const twilio = require("twilio");
const VoiceResponse = require("twilio/lib/twiml/VoiceResponse");

//const phoneNumber = "+12065908374"; //estos 2 se toman del perfil de numero de telefonos dando clic numero activo y seleccionar un numero
//const phoneNumberSid = "PN83bfe991caced8974ca714a6ba42e6ce"; //estos 2 se toman del perfil de numero de telefonos dando clic numero activo y seleccionar un numero
//const tokenSid = "SKd3ec96c12fe3d109ad454e30f293aaaa"; //este ir a Account > API keys y token crear una api en este caso se llama callcenter
//const tokenSecret = "ND4woHpK6QWlG4vT3RY8Gvw75E2gWlAw"; //este ir a Account > API keys y token de la creacion de api llamada callcenter da el secret
//const accountSid = "AC8160c5f5d14d4c87edf58ed296a9dd7a"; // este esta en dashboard
//const verify = "VAc87febaf4c11e2f5fbf9cd24b2efb4f7"; // este primero debemos agregar el producto llamada Verify luego crear un servicio lo llamare callcenter copiaremos el Service SID
//const outgoingApplicationSid = "AP9bac81ce19ec70fcab5f1ce07643028c"; //esta esta en Voice > TwiML apps. luego crear una y aplicar las api en la opciones y copial el campo con nombre TwiML App SID

class Twilio {
   phoneNumber = "+1 415 521 1165";
   phoneNumberSid = "PNe9049b2f1aa083cd294f62f85afbde81";
   //tokenSid = "SKd3ec96c12fe3d109ad454e30f293aaaa";
   //tokenSecret = "ND4woHpK6QWlG4vT3RY8Gvw75E2gWlAw";
   tokenSid = "SK851fd5bebfd780f7836aa3b6ab9234e1";
   tokenSecret = "3D7JvHxAyohSJJ0tM1uF2UZmIixrOqs5";
   accountSid = "ACbed13a7af74fcf734b77b8069cfbeedd";
   verify = "VA311aa93774cbcedfcc4b7f0059c883b7";
   outgoingApplicationSid = "AP9bac81ce19ec70fcab5f1ce07643028c";

   client;

   constructor() {
      /* this.client = twilio(this.tokenSid, this.tokenSecret, {
         accountSid: this.accountSid,
      }); */

      this.client = twilio(this.accountSid, "0ef4fa3357c760c16bd4472cbe4c4113");
   }

   getTwilio() {
      this.client;
   }

   async sendVerifyAsync(to, channel) {
      try {
         const data = await this.client.verify.v2
            .services(this.verify)
            .verifications.create({
               to,
               channel,
            });
         console.log("sendVerify:", data);
         return 1;
      } catch (error) {
         return "error al enviar codigo: " + error.message;
      }
   }

   async verifyCodeAsync(to, code) {
      try {
         const data = await this.client.verify.v2
            .services(this.verify)
            .verificationChecks.create({
               to,
               code,
            });
         console.log("verifyCode:", data);
         return data;
      } catch (error) {
         return "error al verificar codigo: " + error.message;
      }
   }

   voiceResponse(message) {
      const twiml = new VoiceResponse();
      /*  twiml.say(
         {
            voice: "female",
         },
         message,
      );
      twiml.redirect("https://icaro-callcenter.loca.lt/enqueue");
      return twiml; */

      twiml.say(
         {
            voice: "Polly.Bianca",
            //loop: 2,
         },
         message,
      );
      twiml.redirect("https://callcenter.loca.lt/enqueue");
      return twiml;
   }

   enqueueCall(queueName) {
      const twiml = new VoiceResponse();
      twiml.enqueue(queueName);
      return twiml;
   }

   redirectCall(client) {
      const twiml = new VoiceResponse();
      twiml.dial().client(client);
      return twiml;
   }

   answerCall(sid) {
      console.log("answerCall with sid", sid);
      this.client.calls(sid).update({
         url: "https://callcenter.loca.lt/connect-call",
         method: "POST",
         function(err, call) {
            console.log("anwserCall", call);
            if (err) {
               console.error("anwserCall error", err);
            }
         },
      });
   }

   getAccessTokenForVoice = (identity) => {
      console.log(`Access token for ${identity}`);
      const AccessToken = twilio.jwt.AccessToken;
      const VoiceGrant = AccessToken.VoiceGrant;
      const outgoingAppSid = this.outgoingApplicationSid;
      const voiceGrant = new VoiceGrant({
         outgoingApplicationSid: outgoingAppSid,
         incomingAllow: true,
      });
      const token = new AccessToken(
         this.accountSid,
         this.tokenSid,
         this.tokenSecret,
         { identity },
      );
      token.addGrant(voiceGrant);
      console.log("Access granted with JWT", token.toJwt());
      return token.toJwt();
   };
}

const instance = new Twilio();
Object.freeze(instance);

module.exports = instance;
