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

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

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

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

const globalTables = require('../tools/globalTables');

const _ = require('lodash');


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);

  if (req.user && req.user.username) {
    User.setOnLine(req.user.idapp, req.user.username);
  }

  const check = tools.checkUserOk(myrecmsg.origin, 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) => {
          const myrecsend = new SendNotif(
            {
              title: recmsg.source.infoevent,
              sender: recmsg.origin,
              dest: recmsg.dest,            
              openUrl: '',
            });
          // Add this field because I don't want to add into the database
          // myrecsend.source.infoevent = body.source.infoevent;

          myrecsend.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS;
          myrecsend.typeid = shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG;
          myrecsend.msg = recmsg.message;
          let myid = recmsg._id;
          // ##Todo !! DA SISTEMARE !!!
          return await SendNotif.saveAndSendNotif(myrecsend, req, res, null).then((out) => {
            if (out)
              return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: myid });
            else
              return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
          })

        });
    }).catch((e) => {
      console.error(e.message);
      // res.status(400).send(e);
      // return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
    })

  let fine = '';

});

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 && req.user.username) {
    User.setOnLine(req.user.idapp, req.user.username);
  }

  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;
