const express = require("express");
const twilio = require("./Twilio");
const bodyParser = require("body-parser");
const cors = require("cors");
const http = require("http");
const socketIo = require("socket.io");
const jwt = require("./utils/Jwt");
const { getAccessTokenForVoice } = require("./Twilio");

const app = express();
const server = http.createServer(app);

const io = socketIo(server, {
   cors: {
      origin: "*",
      //methods: ["*"],
   },
   path: "/twilio-node-js/socket.io",
});

/* io.use((socket, next) => {
   console.log("Socket middleware");
   if (socket.handshake.query && socket.handshake.query.token) {
      const { token } = socket.handshake.query;
      try {
         const result = jwt.verifyToken(token);
         if (result.username) return next();
      } catch (error) {
         console.log(error);
      }
   }
}); */

io.on("connection", (socket) => {
   console.log("Socket connected", socket.id);
   //socket.emit("twilio-token", { token: getAccessTokenForVoice("cesar") });
   socket.emit("twilio-token", { token: getAccessTokenForVoice("cesar") });
   socket.on("disconnect", () => {
      console.log("Socket disconnected", socket.id);
   });
   socket.on("answer-call", ({ sid }) => {
      console.log("Answering call with sid", sid);
      twilio.answerCall(sid);
   });
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.disable("x-powered-by");
app.use(cors());

const PORT = 30110;
app.get("/twilio-node-js/test", (req, res) => {
   res.send("Welcome to Twilio");
});

app.get("/twilio-node-js/", (req, res) => {
   res.send("El Servidor esta arrancando, felicidades.");
});

app.post("/twilio-node-js/check-token", (req, res) => {
   const { token } = req.body;
   let isValid = false;
   try {
      isValid = jwt.verifyToken(token);
   } catch (error) {
      console.log(error);
   }
   res.send({ isValid });
});

app.post("/twilio-node-js/login", async (req, res) => {
   console.log("loging in ");
   const { to, username, channel } = req.body;
   /* const data = await twilio.sendVerifyAsync(to, channel);
   if (data == 1) {
      res.send("Sent Code");
   } else {
      res.send(data);
   } */

   res.send("Sent Code");
});

app.post("/twilio-node-js/verify", async (req, res) => {
   console.log("Verifing code");
   const { to, code, username } = req.body;
   /*  const data = await twilio.verifyCodeAsync(to, code);

   if (data.status === "approved") {
      const token = jwt.createJwt(username);
      return res.send({ token });
   }
   res.status(200).send("Invalid token"); */

   let token = getAccessTokenForVoice("cesar");
   return res.send({ token });
});

//webhooks cuando una persona llama, pasa por el twilio.voiceResponse y de ahi por la api app.post("/enqueue"
app.post("/twilio-node-js/call-new", (req, res) => {
   //console.log("receive a new call: ", req.body);
   console.log("receive a new call ");

   io.emit("call-new", { data: req.body });
   const response = twilio.voiceResponse("Espera por favor");
   res.type("text/xml");
   res.send(response.toString());
});

//webhook para ver el estado
app.post("/twilio-node-js/call-status-changed", (req, res) => {
   //console.log("Call status changes: ", req.body);
   console.log("Call status changes");
   res.send("Call status changes");
});

app.post("/twilio-node-js/enqueue", (req, res) => {
   const response = twilio.enqueueCall("Customer Service");
   console.log("Enqueuing call");
   io.emit("enqueue", { data: req.body });
   res.type("text/xml");
   res.send(response.toString());
});

app.post("/twilio-node-js/connect-call", (req, res) => {
   console.log("Connecting call");
   const response = twilio.redirectCall("cesar");
   res.type("text/xml");
   res.send(response.toString());
});

//console.log(process.env.MOBILE);

server.listen(PORT, () => {
   console.log(`Listening on PORT: ${PORT}`);
});
