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

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

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

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

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

const _ = require('lodash');

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

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

  const recout = await SendNotif.saveAndSendNotif(myrecnotif, req, res, null);
  if (recout) {
    return res.send({ code: server_constants.RIS_CODE_OK, notif: '', record: recout });
  } else {
    return res.send({ code: server_constants.RIS_CODE_ERR, notif: '' });
  }
});

router.get('/setall/:username/:qualinotif/:idapp', authenticate, async (req, res) => {
  const idapp = req.params.idapp;
  const username = req.params.username;
  const qualinotif = parseInt(req.params.qualinotif);
  const username_call = req.user.username;

  try {
    if (username === username_call) {
      let query = { idapp, dest: username, read: false };

      if (qualinotif === shared_consts.QualiNotifs.CIRCUITS) {
        query.typedir = { $eq: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
      } else if (qualinotif === shared_consts.QualiNotifs.OTHERS) {
        query.typedir = { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
      }
      const arrNotifs = await SendNotif.find(query).lean();
      if (arrNotifs) {
        for (const rec of arrNotifs) {
          await SendNotif.setNotifAsRead(idapp, username_call, rec._id);
        }
      }

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

router.get('/set/:_id/:idapp', authenticate, async (req, res) => {
  const _id = req.params._id;
  const username_call = req.user.username;

  try {
    let query = { _id, dest: username_call, read: false };

    const rec = await SendNotif.findOne(query);
    if (rec) {
      rec.read = true;
      await rec.save();
      return res.send(true);
    }
    res.send(false);
  } catch (e) {
    res.status(400).send(e);
  }
});

async function delNotif(res, idapp, username, id, username_call) {
  try {
    if (username === username_call) {
      await SendNotif.findOneAndDelete({ idapp, _id: id });
      return res.send(true);
    }
  } catch (e) {
    return res.status(400).send(e);
  }

  return res.send(false);
}

router.get('/del/:username/:id/:idapp', authenticate, async (req, res) => {
  try {
    return delNotif(res, req.params.idapp, req.params.username, req.params.id, req.user.username);
  } catch (e) {
    return res.status(400).send(e);
  }
});

router.get('/delall/:username/:qualinotif/:idapp', authenticate, async (req, res) => {
  const idapp = req.params.idapp;
  const username = req.params.username;
  const qualinotif = parseInt(req.params.qualinotif);
  const username_call = req.user.username;

  try {
    if (username === username_call) {
      let query = { idapp, dest: username };

      if (qualinotif === shared_consts.QualiNotifs.CIRCUITS) {
        query.typedir = { $eq: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
      } else if (qualinotif === shared_consts.QualiNotifs.OTHERS) {
        query.typedir = { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
      }
      const ris = await SendNotif.deleteMany(query);
      if (ris) return res.send(true);
    }
  } catch (e) {
    return res.status(400).send(e);
  }

  return res.send(false);
});

router.get('/:username/:lastdataread/:idapp', authenticate_noerror, (req, res) => {
  return getNotif(req, res);
});

async function getNotif(req, res) {
  try {
    // 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) {
      return res.status(200).send();
    }

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

    const arrnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(
      username,
      lastdataread,
      idapp,
      shared_consts.LIMIT_NOTIF_FOR_USER,
      shared_consts.QualiNotifs.OTHERS
    );
    let arrnotifcoins_inattesa = null;

    if (await User.isAdminByUsername(idapp, req.user.username)) {
      arrnotifcoins_inattesa = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
    } else {
      arrnotifcoins_inattesa = await SendNotif.findAllNotifByUsernameIdAndIdApp(
        username,
        lastdataread,
        idapp,
        shared_consts.LIMIT_NOTIFCOINS_IN_ATTESA_FOR_USER,
        shared_consts.QualiNotifs.CIRCUITS,
        [{ status: 0 }]
      );
    }

    const arrnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(
      username,
      lastdataread,
      idapp,
      shared_consts.LIMIT_NOTIFCOINS_FOR_USER,
      shared_consts.QualiNotifs.CIRCUITS,
      [{ status: { $ne: 0 } }]
    );

    //++Todo: Ottimizzare ! Non occorre inviare tutti questi dati !!! Solo per il Circuito ?!
    const userprofile = await User.getExtraInfoByUsername(idapp, req.user.username);

    return res.send({ arrnotif, arrnotifcoins: [...arrnotifcoins, ...arrnotifcoins_inattesa], userprofile });
  } catch (e) {
    console.log(e.message);
    res.status(400).send(e);
  }
}

module.exports = router;
