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

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

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

const { Booking } = require('../models/booking');

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

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

const _ = require('lodash');

const sendNotifBooking = async (res, idapp, user, recbooking) => {
  //++Todo: tools.sendNotificationToUser

  // Send Email
  if (recbooking.booked)
    return await sendemail.sendEmail_Booking(res, user.lang, user.email, user, idapp, recbooking);
  else
    return await sendemail.sendEmail_CancelBooking(res, user.lang, user.email, user, idapp, recbooking);
};

router.post('/', authenticate_withUser, (req, res) => {
  // tools.mylog('INIZIO - booking');
  // tools.mylog('req.body', req.body);
  const myrec = _.pick(req.body, tools.allfieldBooking());
  const id = myrec.id_bookedevent;
  const fieldtochange = _.pick(myrec, tools.allfieldBookingChange());

  tools.mylog('crea Booking');
  const booking = new Booking(myrec);

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

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

  // Modify:
  return Booking.findOne({ id_bookedevent: id, userId: req.user._id })
    .then(trovato => {
      // console.log('trovato', trovato);
      if (trovato) {
        return Booking.findOneAndUpdate({ id_bookedevent: id }, { $set: fieldtochange }, {
          new: true,
          upsert: true
        }).then((recbooking) => {
          // tools.mylog('booking:', booking);
          // tools.mylog('already exist');
          sendNotifBooking(res, myrec.idapp, req.user, myrec);
          return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id });
        });
      } else {
        // save to database a new record
        tools.mylog('save to database a new record');
        booking._id = new ObjectId();
        return booking.save().then((writeresult) => {
          let idobj = writeresult._id;

          Booking.findById(idobj)
            .then((recbooking) => {
              sendNotifBooking(res, myrec.idapp, req.user, writeresult);
              return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: writeresult._id });
            });
        });
      }
    }).catch((e) => {
      console.error('Error', e);
      return res.status(400).send();
    });
});

router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
  console.log('DELETE Booking');
  const id = req.params.id;
  const notify = req.params.notify;
  const idapp = req.params.idapp;
  
  Booking.findOneAndDelete({_id: id}).then((recbooking) => {
    if (!recbooking) {
      return res.status(404).send();
    }

    if (notify === '1') {
      recbooking.booked = false;
      sendNotifBooking(res, idapp, req.user, recbooking);
    }

    tools.mylog('DELETED ', recbooking._id);

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

  }).catch((e) => {
    return 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 BOOKINGS : ', 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
//   const bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall);
//   const eventlist = MyEvent.findAllIdApp(idapp);
//   const operators = Operator.findAllIdApp(idapp);
//   const wheres = Where.findAllIdApp(idapp);
//   const contribtype = Contribtype.findAllIdApp(idapp);
//
//   return Promise.all([bookedevent, eventlist, operators, wheres, contribtype])
//     .then((arrdata) => {
//       console.table(arrdata);
//       res.send({ bookedevent: arrdata[0], eventlist: arrdata[1], operators: arrdata[2], wheres: arrdata[3], contribtype: arrdata[4] });
//     })
//     .catch((e) => {
//       console.log(e.message);
//       res.status(400).send(e);
//     });
//
// });
//

module.exports = router;
