const config = require("config");
const admin = require("firebase-admin");
const moment = require("moment");
const serviceAccount = require("../../../firebase.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

module.exports.singleNotification = ({ token, title, body }) =>
  new Promise(async (resolve, reject) => {
    try {
      console.log("FCM TOKEN: ", token);
      admin
        .messaging()
        .send({
          token: token,
          notification: {
            title,
            body,
          },
        })
        .then((response) => {
          console.log("Message were sent successfully", response);
          resolve(response);
        })
        .catch((err) => {
          console.log("Error in sending msg internally: ", err);
          reject({
            message:
              err.message || "Something went wrong in sending notification!",
          });
        });
    } catch (error) {
      console.log("ERROR in single", error);
      resolve();
      // reject(error);
    }
  });

module.exports.multipleNotification = ({ tokens, title, body }) =>
  new Promise(async (resolve, reject) => {
    try {
      admin
        .messaging()
        .sendMulticast({
          tokens: tokens,
          notification: {
            title,
            body,
          },
        })
        .then((response) => {
          if (response.failureCount > 0) {
            const failedTokens = [];
            response.responses.forEach((resp, idx) => {
              if (!resp.success) {
                failedTokens.push(tokens[idx]);
                console.log("Token that caused failures: " + tokens[idx]);
              }
            });
            console.log("List of tokens that caused failures: " + failedTokens);
            return resolve({ message: "Successfully sent notifications!" });
          }
          console.log("Messages were sent successfully", response);
          return resolve({ message: "Successfully sent notifications!" });
        })
        .catch((err) => {
          console.log("Error in sending msg internally: ", err);
          reject({
            message:
              err.message || "Something went wrong in sending notification!",
          });
        });
    } catch (error) {
      // reject(error);
      resolve();
    }
  });

module.exports.createNotification = (to, msg, from, activity) =>
  new Promise(async (resolve, reject) => {
    try {
      let currentTime = moment().format("YYYY-MM-DD HH:mm:ss");

      var x = `insert into notification (fromUser, toUser, msg, type,createdAt, updatedAt) values
       ('${from}', '${to}', '${msg}', '${activity}', '${currentTime}', '${currentTime}')`;
      await db.query(x);
      resolve();
    } catch (error) {
      console.log("ERROR in createNotification", error);
      resolve();
    }
  });

module.exports.getChatPersonImage = (chatHeaders, currentUser, flag) =>
  new Promise(async (resolve, reject) => {
    try {
      let user = null;
      if (chatHeaders[flag].userId && chatHeaders[flag].userId != currentUser) {
        var x = `select avatar from users where id = '${chatHeaders[flag].userId}'`;
        let users = await db.query(x);
        user = users[0];
        chatHeaders[flag].avatar = user.avatar;
        // console.log("USER: ", user);
      } else if (
        chatHeaders[flag].userId2 &&
        chatHeaders[flag].userId2 != currentUser
      ) {
        var x = `select avatar from users where id = '${chatHeaders[flag].userId2}'`;
        let users = await db.query(x);
        user = users[0];
        chatHeaders[flag].avatar = user.avatar;
        // console.log("USER: ", user);
      }
      resolve(chatHeaders);
    } catch (error) {
      reject(error);
    }
  });
