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

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

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

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

const {SendNotif} = require('../models/sendnotif');

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

const _ = require('lodash');

router.post('/', authenticate, (req, res) => {
  tools.mylog('INIZIO - MyEvent');

  // tools.mylog('req.body', req.body);
  const myrec = _.pick(req.body, tools.allfieldMyEvent());
  const id = myrec._id;
  const fieldtochange = _.pick(myrec, tools.allfieldMyEventChange());

  tools.mylog('crea MyEvent');
  const myevent = new MyEvent(myrec);

  const check = tools.checkUserOk(myevent.userId, req.user._id, res);
  if (check.exit) return check.ret;

  // Modify:
  return MyEvent.findOne({id}).then((trovato) => {
    // console.log('trovato', trovato);
    if (trovato) {
      return myevent.findOneAndUpdate({id}, {$set: fieldtochange}, {
        new: false,
        upsert: true,
      }).then(async (recmyevent) => {
        // tools.mylog('myevent:', myevent);
        // tools.mylog('already exist');
        SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
        return res;
      }).then((res) => {
        res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
      });
    } else {
      // save to database a new record
      tools.mylog('save to database a new record');
      myevent._id = new ObjectID();
      return myevent.save().then((writeresult) => {
        let idobj = writeresult._id;

        myevent.findById(idobj).then((recmyevent) => {
          recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
          recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC
          SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
          return res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});
        });
      });
    }
  });
});

router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
  console.log('DELETE myevent');
  const id = req.params.id;
  const notify = req.params.notify;
  const idapp = req.params.idapp;

  myevent.findByIdAndRemove(id).then((recmyevent) => {
    if (!recmyevent) {
      return res.status(404).send();
    }

    if (notify === '1') {
      SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC);
    }

    tools.mylog('DELETED ', recmyevent.descr, recmyevent._id);

    res.send({code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id});

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

router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
  const userId = req.params.userId;
  const idapp = req.params.idapp;
  const sall = req.params.sall;
  // var category = req.params.category;

  // tools.mylog('GET myeventS : ', req.params);

  if (!ObjectID.isValid(userId)) {
    return res.status(404).send();
  }

  if (userId !== String(req.user._id)) {
    // I'm trying to write something not mine!
    return res.status(404).send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER});
  }

  // Extract all the todos of the userId only
  return MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => {
    res.send({recevent});
  }).catch((e) => {
    console.log(e.message);
    res.status(400).send(e);
  });

});

module.exports = router;
