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 { Nave } = require('../models/nave');
const { NavePersistente } = require('../models/navepersistente');

const mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');

const telegrambot = require('../telegram/telegrambot');

const _ = require('lodash');

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

router.post('/', authenticate, async (req, res) => {
  try {
    const idapp = req.body.idapp;
    let username = req.body.username;

    if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (username) !== req.user.username) {
      // If without permissions, exit
      return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
    }
    let aportador_solidario = req.user.aportador_solidario;
    let aportador_solidario_nome_completo = req.user.aportador_solidario_nome_completo;

    // if (User.isAdmin(req.user.perm) || User.isManager(req.user.perm)) {
    //   const recuser = await User.findByUsername(idapp, username);
    //   if (recuser) {
    //     aportador_solidario_nome_completo = recuser.name + ' ' + recuser.surname;
    //   }
    // }

    if (username) {
      aportador_solidario = await User.getAportadorSolidarioByUsername(idapp, username);
      aportador_solidario_nome_completo = await User.getNameSurnameByUsername(idapp, username);
    } else {
      username = req.user.username;
    }

    const dashboard = await User.getDashboard(idapp, aportador_solidario, username, aportador_solidario_nome_completo);
    if (dashboard)
      res.send({ dashboard });
    else
      res.status(400).send(e);

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

});


router.post('/msgnave', authenticate, async (req, res) => {
  const idapp = req.body.idapp;
  let mydata = req.body;

  try {

    let ris = null;
    if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) {
      let mymsg = '';
      if (!!mydata.username_mitt) {
        mymsg = '[' + tools.getres__('MSG_SEND_FROM', res) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO;
      }
      mymsg += mydata.msgpar1;
      ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true, mydata.username_mitt);  // Anche a STAFF
    } else
      ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata);

    if (ris)
      res.send({ code: server_constants.RIS_CODE_OK, ris });
    else
      res.send({ code: server_constants.RIS_CODE_ERR, ris: null });


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

});

router.post('/getnave', authenticate, async (req, res) => {
  const idapp = req.body.idapp;
  const riga = req.body.riga;
  const col = req.body.col;
  const riga1don = req.body.riga1don;
  const col1don = req.body.col1don;
  const ind_order = req.body.ind_order;

  const nave = await NavePersistente.findByRigaCol(idapp, riga, col);
  if (!!nave) {
    nave._doc.rec = await Nave.getNaveByRigaCol(idapp, riga1don, col1don);
    if (ind_order >= 0)
      nave._doc.ind_order = ind_order;

    nave._doc.listadonatoridelsognatore = await Nave.getDonatoridelSognatore(idapp, riga1don, col1don);
  }

  const navi_partenza = await NavePersistente.findAllIdApp(idapp);

  ris = { nave, navi_partenza };

  if (ris)
    res.send({ code: server_constants.RIS_CODE_OK, ris });
  else
    res.status(400).send(e);

});

router.post('/getnavi', authenticate, async (req, res) => {
  const idapp = req.body.idapp;

  let arrnavi = await NavePersistente.findAllIdApp(idapp);

  for (nave of arrnavi) {
    //nave.rec = await Nave.getNaveByRigaCol(idapp, nave.riga, nave.col);
    nave._doc.rec = {
      donatore: {},
      mediatore: null
    };

    let riganave = nave.riga;
    let colnave = nave.col;
    // if (riganave < 4) {
    //   riganave = 4;
    //   colnave = 1;
    // }
    // nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, riganave, colnave, 0);
    nave._doc.rec.donatore.navepersistente = await NavePersistente.findOne({ idapp, riga: riganave, col: colnave });
  }

  const navi_partenza = await NavePersistente.findAllIdApp(idapp);

  ris = { arrnavi, navi_partenza };

  if (ris)
    res.send({ code: server_constants.RIS_CODE_OK, ris });
  else
    res.status(400).send(e);

});

router.post('/getdoninavi', authenticate, async (req, res) => {
  const idapp = req.body.idapp;
  const ricalcola = req.body.ricalcola;

  let arrnavi = await NavePersistente.findAllIdApp(idapp);
  let test = false;

  //arrnavi.push({ riga: indriga, col: indcol, rigadon: indriga + 3, coldon: (indcol * 8) - 7 });

  try {
    if (ricalcola) {
      let index = 1;

      for (nave of arrnavi) {
        nave = await Nave.ricalcolaNave(idapp, nave, 0, 0, ricalcola, index);
        index++;
      }
    } else {
      arrnavi = await NavePersistente.findAllIdApp(idapp);
      for (nave of arrnavi) {
        if (nave.provvisoria || nave.DoniTotali !== nave.DoniConfermati) {
          nave._doc.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don);
        } else {
          let rigapos = nave.riga1don;
          let colpos = nave.col1don;
          if (rigapos < 4) {
            rigapos = 4;
            colpos = 1;
          }
          nave._doc.rec = {};
          nave._doc.rec.donatore = {};
          nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, rigapos, colpos, tools.Placca.SONOFUOCO);
        }
      }
    }

    ris = { arrnavi };

    if (ris)
      res.send({ code: server_constants.RIS_CODE_OK, ris });
    else
      res.status(400).send(e);
  } catch (e) {
    console.log(e.message)
  }

});

router.post('/getdata', authenticate, async (req, res) => {
  const idapp = req.body.idapp;
  const data = req.body.data;

  try {

    const mystr = await Nave.getNavePos(idapp, parseInt(data.riga), parseInt(data.col));

    if (mystr)
      res.send({ code: server_constants.RIS_CODE_OK, ris: mystr });
    else
      res.status(400).send(e);
  } catch (e) {
    console.log(e.message)
  }

});


module.exports = router;
