const express = require('express');
const router = express.Router();

const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');

const { authenticate } = require('../middleware/authenticate');

const { User } = require('../models/user');
const { Operator } = require('../models/operator');
const { SendMsg } = require('../models/sendmsg');

const { ObjectID } = require('mongodb');

const sendemail = require('../sendemail');

const shared_consts = require('../tools/shared_nodejs');

const _ = require('lodash');

function checkifSendPushNotification() {
  return process.env.ENABLE_PUSHNOTIFICATION === "1";
  //return false;
}


async function sendNotif(res, idapp, user, recmsg) {
  if (tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
    if (this.checkifSendPushNotification) {
      console.log('SEND PUSH NOTIFICATION ')
      //++Todo: tools.sendNotificationToUser

    }
  }

  // Read from the operator table first
  let emaildest = await Operator.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
  if (emaildest === '')
    emaildest = await User.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);

  console.log('emaildest', emaildest);

  // Send Msg by EMAIL
  if (emaildest && tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByEmail))
    await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recmsg);

  return true
}

router.post('/', authenticate, (req, res) => {
  tools.mylog('INIZIO - SendMsg');
  // tools.mylog('req.body', req.body);
  const body = _.pick(req.body, tools.allfieldSendMsg());

  tools.mylog('crea SendMsg');
  const myrecmsg = new SendMsg(body);

  const check = tools.checkUserOk(myrecmsg.origin.username, req.user.username, res);
  if (check.exit) return check.ret;

  // console.log('fieldtochange', fieldtochange);

  myrecmsg._id = new ObjectID();
  return myrecmsg.save()
    .then((writeresult) => {
      let idobj = writeresult._id;

      myrecmsg._id = idobj;

      return SendMsg.findById(idobj)
        .then(async (recmsg) => {
          // Add this field because I don't want to add into the database
          recmsg.source.infoevent = body.source.infoevent;

          return await sendNotif(res, body.idapp, req.user, recmsg).then((ris) => {
            return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
          })
        });
    }).catch((e) => {
      console.log(e.message);
      // res.status(400).send(e);
      return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
    })

});

router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
  tools.mylog('GET SendMsgS : ', req.params);
  const username = req.params.username;
  const lastdataread = req.params.lastdataread;
  const idapp = req.params.idapp;
  // var category = req.params.category;

  if (req.user.idapp !== idapp) {
    // I'm trying to get something not mine!
    return res.status(404).send({ code: server_constants.RIS_CODE_NOT_MY_USERNAME });
  }


  // Extract all the todos of the userId only
  return SendMsg.findAllMsgByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrmsg) => {
    // const wait = new Promise((resolve, reject) => {
    // setTimeout(() => {
    res.send({ arrmsg });
    // }, 2000);
    // });

  }).catch((e) => {
    console.log(e.message);
    res.status(400).send(e);
  });

});


module.exports = router;
