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 { SendNotif } = require('../models/sendnotif');

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

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

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

const _ = require('lodash');


async function sendNotif(res, idapp, user, recnotif) {
  // Controlla nelle impostazioni che tipo di Notifica visualizzare


  if (tools.isBitActive(recnotif.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(recnotif.dest.idapp, recnotif.dest.username);
  if (!emaildest)
    emaildest = await User.getEmailByUsername(recnotif.dest.idapp, recnotif.dest.username);

  console.log('emaildest', emaildest);

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

  return true
}

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

  tools.mylog('crea SendNotif');
  const myrecnotif = new SendNotif(body);

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

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

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

      myrecnotif._id = idobj;

      return SendNotif.findById(idobj)
        .then(async (recnotif) => {
          // Add this field because I don't want to add into the database

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

});

router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
  tools.mylog('GET NotifS : ', 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 SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrnotif) => {
    // const wait = new Promise((resolve, reject) => {
    // setTimeout(() => {
    res.send({ arrnotif });
    // }, 2000);
    // });

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

});


module.exports = router;
