const express = require('express');
const router = express.Router(),
  fs = require('fs'),
  path = require('path');

const jwt = require('jsonwebtoken');

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

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

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

const { ObjectID } = require('mongodb');
const { ListaIngresso } = require('../models/listaingresso');

const mongoose = require('mongoose');
const cfgserver = mongoose.model('cfgserver');

const ftp = require('../ftp/FTPClient'),
  formidable = require('formidable'),
  folder = path.join(__dirname, 'upload');

if (!fs.existsSync(folder)) {
  fs.mkdirSync(folder)
}

const _ = require('lodash');

const { User } = require('../models/user');
const { Nave } = require('../models/nave');
const { NavePersistente } = require('../models/navepersistente');
// const { ExtraList } = require('../models/extralist');
const { Booking } = require('../models/booking');
const { Operator } = require('../models/operator');
const { Where } = require('../models/where');
const { MyEvent } = require('../models/myevent');
const { Contribtype } = require('../models/contribtype');
const { PaymentType } = require('../models/paymenttype');
const { Discipline } = require('../models/discipline');
const { Newstosent } = require('../models/newstosent');
const { MyPage } = require('../models/mypage');
const { CalZoom } = require('../models/calzoom');
const { Gallery } = require('../models/gallery');
const { TemplEmail } = require('../models/templemail');
const { OpzEmail } = require('../models/opzemail');
const { MailingList } = require('../models/mailinglist');
const { Settings } = require('../models/settings');
const { SendMsg } = require('../models/sendmsg');
const { Permission } = require('../models/permission');


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

const server_constants = require('../tools/server_constants');
const actions = require('./api/actions');

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

UserCost = {
  FIELDS_REQUISITI: ['verified_email',
    'profile.teleg_id',
    'profile.saw_zoom_presentation',
    'profile.saw_and_accepted',
    'profile.email_paypal',
    'profile.my_dream',
    'profile.paymenttypes']
};

router.post(process.env.LINKVERIF_REG, (req, res) => {
  const body = _.pick(req.body, ['idapp', 'idlink']);
  const idapp = body.idapp;
  const idlink = body.idlink;
  // console.log("LINKVERIF_REG POST " + process.env.LINKVERIF_REG + " idapp= " + idapp + " idlink = " + idlink);

  // Cerco l'idlink se è ancora da Verificare

  User.findByLinkreg(idapp, idlink).then((user) => {
    if (!user) {
      //console.log("NON TROVATO!");
      return res.status(404).send();
    } else {
      console.log('user', user);
      if (user.verified_email) {
        res.send({
          code: server_constants.RIS_CODE_EMAIL_ALREADY_VERIFIED,
          msg: tools.getres__("L'Email è già stata Verificata", res)
        });
      } else {
        user.verified_email = true;
        user.lasttimeonline = new Date();
        user.save().then(() => {
          //console.log("TROVATOOOOOO!");
          res.send({
            code: server_constants.RIS_CODE_EMAIL_VERIFIED,
            msg: tools.getres__('EMAIL', res) + ' ' + tools.getres__('VERIF', res)
          });
        });
      }
    }
  }).catch((e) => {
    console.log(e.message);
    res.status(400).send();
  });

});


// Faccio richiesta di una Nuova Password
router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => {
  const body = _.pick(req.body, ['idapp', 'email']);
  const idapp = body.idapp;
  const email = body.email.toLowerCase().trim();
  console.log("POST " + process.env.LINK_REQUEST_NEWPASSWORD + " idapp= " + idapp + " email = " + email);

  User.findByEmail(idapp, email).then(async (user) => {
    if (!user) {
      await tools.snooze(5000);
      return res.status(200).send({ code: server_constants.RIS_CODE_EMAIL_NOT_EXIST, msg: '' });
    } else {
      // Creo il tokenforgot
      user.tokenforgot = jwt.sign(user._id.toHexString(), process.env.SIGNCODE).toString();
      user.date_tokenforgot = new Date();
      user.lasttimeonline = new Date();
      user.save().then(async () => {
        await sendemail.sendEmail_RequestNewPassword(res.locale, user, user.email, user.idapp, user.tokenforgot);
        res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
      });
    }
  }).catch((e) => {
    console.log(e.message);
    res.status(400).send();
    res.send({ code: server_constants.RIS_CODE_ERR, msg: e });
  });

});


// Invio la Nuova Password richiesta dal reset!
// Ritorna il token per poter effettuare le chiamate...
router.post(process.env.LINK_UPDATE_PWD, (req, res) => {
  const body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'password']);
  const idapp = body.idapp;
  const email = body.email.toLowerCase().trim();
  const tokenforgot = body.tokenforgot;
  const password = body.password;
  const msg = "Richiesta Nuova Password: idapp= " + idapp + " email = " + email;
  console.log(msg);

  // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);

  User.findByLinkTokenforgot(idapp, email, tokenforgot).then((user) => {
    if (!user) {
      return res.send({ code: server_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND });
    } else {
      // aggiorna la nuova password
      user.password = password;
      user.lasttimeonline = new Date();

      // Crea token
      user.generateAuthToken(req).then(token => {
        user.tokenforgot = '';  // Svuota il tokenforgot perché non ti servirà più...

        // Salva lo User
        user.save().then(() => {
          res.header('x-auth', token).send({ code: server_constants.RIS_CODE_OK });   // Ritorna il token di ritorno
        });
      })
    }
  }).catch((e) => {
    console.log(e.message);
    res.status(400).send();
  });

});

function getTableByTableName(tablename) {

  mytable = '';
  if (tablename === 'users')
    mytable = User;
  else if (tablename === 'tessitura')
    mytable = Tessitura;
  // else if (tablename === 'extralist')
  //   mytable = ExtraList;
  else if (tablename === 'bookings')
    mytable = Booking;
  else if (tablename === 'operators')
    mytable = Operator;
  else if (tablename === 'sendmsgs')
    mytable = SendMsg;
  else if (tablename === 'wheres')
    mytable = Where;
  else if (tablename === 'myevents')
    mytable = MyEvent;
  else if (tablename === 'contribtype')
    mytable = Contribtype;
  else if (tablename === 'paymenttypes')
    mytable = PaymentType;
  else if (tablename === 'disciplines')
    mytable = Discipline;
  else if (tablename === 'newstosent')
    mytable = Newstosent;
  else if (tablename === 'gallery')
    mytable = Gallery;
  else if (tablename === 'mypage')
    mytable = MyPage;
  else if (tablename === 'calzoom')
    mytable = CalZoom;
  else if (tablename === 'templemail')
    mytable = TemplEmail;
  else if (tablename === 'opzemail')
    mytable = OpzEmail;
  else if (tablename === 'settings')
    mytable = Settings;
  else if (tablename === 'permissions')
    mytable = Permission;
  else if (tablename === 'mailinglist')
    mytable = MailingList;
  else if (tablename === 'navi')
    mytable = Nave;
  else if (tablename === 'navepersistente')
    mytable = NavePersistente;
  else if (tablename === 'listaingressos')
    mytable = ListaIngresso;

  return mytable
}

router.post('/settable', authenticate, (req, res) => {
  const params = req.body;
  const mytable = getTableByTableName(params.table);
  const mydata = req.body.data;

  mydata.idapp = req.user.idapp;

  if (params.table === 'permissions') {
    if (mydata["_id"] === undefined) {
      mydata._id = 1;
    }
  } else {
    if (mydata["_id"] === undefined) {
      mydata._id = new ObjectID()
    }
  }


  mytablerec = new mytable(mydata);
  console.log('mytablerec', mytablerec);


  return mytablerec.save()
    .then(rec => {
      // tools.mylog('rec', rec);
      return res.send(rec);

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

});

router.post('/gettable', authenticate, (req, res) => {
  const params = req.body;
  const mytable = getTableByTableName(params.table);
  // console.log('mytable', mytable);
  if (!mytable) {
    console.log(`Table ${params.table} not found`);
    return res.status(400).send({});
  }

  return mytable.executeQueryTable(req.user.idapp, params).then(ris => {
    return res.send(ris);

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

});

async function checkIfSbloccatiRequisiti(idapp, allData, id) {

  if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) {
    // Se già sei dentro la Nave, allora sei OK
    return true;
  }

  // Controlla se Sblocca i 7 requisiti
  const is7req = await User.isUserQualified7(idapp, allData.myuser.username);
  const is9req = await User.isUserQualified9(idapp, allData.myuser.username);

  const userlista = await ListaIngresso.getListaTessByUsername(idapp, allData.myuser.username);
  if (userlista.length === 0) {
    // Se non sono ancora dentro alla lista, allora controllo

    if (!allData.precDataUser.is7req && is7req) {
      // ORA HAI I 7 REQUISITI !
      // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang);
      // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true);  // Anche a STAFF

      if (tools.isAbilitaNave(idapp)) {
        // Aggiungilo alla ListaIngresso
        risingr = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.username, allData.myuser.aportador_iniziale, allData.myuser.lang, true, false);
      }
    }
  }

  if (!allData.precDataUser.is9req && is9req) {
    // ORA HAI I 9 REQUISITI !
    const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.myuser.lang);
    telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, false);  // Anche a STAFF
  }

  // CHECK APORTADOR SOLIDARIO:
  if (!!allData.useraportador) {
/*
    const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario);

    if (!allData.precDataAportador.is9req && is9reqAportador) {
      // ORA HAI I 9 REQUISITI !
      const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang);
      telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true);  // Anche a STAFF
    }
*/
  }

}

async function getInfoUser(idapp, username) {
  return {
    username,
    is7req: await User.isUserQualified7(idapp, username),
    is9req: await User.isUserQualified9(idapp, username),
  }

}

router.patch('/setlang', authenticate, async (req, res) => {
  const username = req.body.data.username;
  const idapp = req.body.idapp;
  const mydata = req.body.data;

  const lang = mydata.lang;

  const fieldsvalue = {
    lang
  };

  if (!!lang) {
    const rec = await User.findByUsername(idapp, username, false);
    let ris = null;
    if (!!rec)
      ris = await User.findByIdAndUpdate(rec.id, { $set: fieldsvalue });

    if (!!ris) {
      return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
    }

    res.status(400).send();
  }

});


router.patch('/chval', authenticate, async (req, res) => {
  // const idapp = req.body.idapp;
  const id = req.body.data.id;
  const idapp = req.body.idapp;
  const mydata = req.body.data;

  const mytable = getTableByTableName(mydata.table);
  const fieldsvalue = mydata.fieldsvalue;

  // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);

  // If I change my record...
  if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTraduttrici(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) {
    // If without permissions, exit
    return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
  }

  const camporequisiti = UserCost.FIELDS_REQUISITI.includes(Object.keys(fieldsvalue)[0]);

  let allData = {};
  if (mydata.table === 'users') {
    if (camporequisiti) {
      allData = {};
      allData.myuser = await User.getUserById(idapp, id);
      allData.precDataUser = await getInfoUser(idapp, allData.myuser.username);
      // allData.useraportador = await ListaIngresso.getUserByInvitante_Username(idapp, allData.myuser.aportador_solidario);
      // allData.precDataAportador = await getInfoUser(idapp, allData.myuser.aportador_solidario);
    }
  }

  let index = 0;

  await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then(async (rec) => {
    // tools.mylogshow(' REC TO MODIFY: ', rec);
    if (!rec) {
      return res.status(404).send();
    } else {
      if (mydata.notifBot) {
        // Send Notification to the BOT
        await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, mydata.notifBot.txt);
        addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt;
        await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true);
      }

      if (mydata.table === 'users') {
        if (camporequisiti) {
          await checkIfSbloccatiRequisiti(idapp, allData, id);
        }
      }

      if (mydata.table === 'users') {
        if ('aportador_solidario' in fieldsvalue) {
          ind_order_ingr = mydata.ind_order_ingr;
          // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username!
          const myuserfound = await User.findByUsername(idapp, fieldsvalue.aportador_solidario, false);
          if (!!myuserfound) {
            if (!!myuserfound._id && !myuserfound.deleted) {
              const aportador = await User.getUsernameById(idapp, myuserfound._id);
              fieldsvalue.aportador_solidario = aportador;
              //Aggiorna record !
              await mytable.findByIdAndUpdate(id, { $set: fieldsvalue });

              const myfirstrec = await ListaIngresso.findOne({ username: rec.username, ind_order: ind_order_ingr });
              if (!!myfirstrec) {
                if (!!myfirstrec._id && !myfirstrec.deleted) {
                  let fieldsv2 = {
                    invitante_username: aportador
                  };
                  //Aggiorna record !
                  const ris = await ListaIngresso.findByIdAndUpdate(myfirstrec._id.toString(), { $set: fieldsv2 });
                }
              }
            }
          } else {
            res.send({ code: server_constants.RIS_CODE_ERR, msg: 'Non aggiornato' });
            res.status(400).send();
            return false;
          }
        }
      }

      if (mydata.table === 'listaingressos') {
        if ('invitante_username' in fieldsvalue) {
          // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username!
          const myuserfound = await User.findByUsername(idapp, fieldsvalue.invitante_username, false);
          if (!!myuserfound) {
            if (!!myuserfound._id && !myuserfound.deleted) {
              fieldsvalue.invitante_username = await User.getUsernameById(idapp, myuserfound._id);
              //Aggiorna record !
              const ris = await mytable.findByIdAndUpdate(id, { $set: fieldsvalue });
              if (!!ris) {
                /*let fieldsv2 = {
                  aportador_solidario: fieldsvalue.invitante_username
                };

                //Aggiorna record !
                await User.findByIdAndUpdate(myuserfound._id, { $set: fieldsv2 });
                */
              }
            }
          } else {
            // res.send({ code: server_constants.RIS_CODE_ERR, msg: 'Non aggiornato' });
            // res.status(400).send();
            // return false;
          }
        }
      }

      if (tools.ModificheConsentite(mydata.table, fieldsvalue)) {
        let msg = '';
        if (mydata.table === 'users') {
          if ('aportador_solidario' in fieldsvalue) {
            const nomecognomenuovo = await User.getNameSurnameByUsername(idapp, fieldsvalue.aportador_solidario);
            const nomecognomeas = await User.getNameSurnameByUsername(idapp, rec.aportador_solidario);
            msg = `Variato l'invitante di ` + rec.name + ' ' + rec.surname + '\nmodificato da ' + req.user.name + ' ' + req.user.surname + ' \n' +
              'Prima: ' + nomecognomeas + ' (' + rec.aportador_solidario + ')\n' +
              'Dopo: ' + nomecognomenuovo + ' (' + fieldsvalue.aportador_solidario + ') ]';

            // Metti l'iniziale
            if (!await User.AportadorOrig(id)) {
              await mytable.findByIdAndUpdate(id, { $set: { aportador_iniziale: fieldsvalue.aportador_solidario } }, { new: false });
            }
          }

        } else if (mydata.table === 'navi') {
          if ('made_gift' in fieldsvalue) {
            if (!!fieldsvalue.riga) {
              await Nave.ricalcolaNave(idapp, null, fieldsvalue.riga, fieldsvalue.col, true, index)
            }
          }
        }

        if (msg !== '')
          telegrambot.sendMsgTelegramToTheManagers(idapp, msg);
      }

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

    }

  }).catch((e) => {
    tools.mylogserr('Error patch USER: ', e.message);
    res.status(400).send();
  })


});

router.patch('/callfunz', authenticate, async (req, res) => {
  // const idapp = req.body.idapp;
  const id = req.body.data.id;
  const ind_order = req.body.data.ind_order;
  const username = req.body.data.username;
  const idapp = req.body.idapp;
  const mydata = req.body.data;

  try {
    let entra = false;
    if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO ||
      mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) {
      entra = true
    }
    if (!entra) {
      // If I change my record...
      if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) {
        // If without permissions, exit
        return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
      }
    }

    const myuser = await User.findOne({ idapp, username });

    let rimosso = 0;


    if (mydata.myfunc === shared_consts.CallFunz.SOSTITUISCI) { // SOSTITUISCI
      mianavedasost = await Nave.findOne({ idapp, riga: mydata.data.riga, col: mydata.data.col });

      // Sostituisci l'Utente
      myusernuovo = await User.getUserShortDataByUsername(idapp, mydata.data.username);
      let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, mydata.data.riga, mydata.data.col, 0);

      if (!!myusernuovo) {
        // Controlla prima se è in una Nave Temporanea, allora lo elimina
        miaarrnavi = await Nave.find({ idapp, ind_order: myusernuovo.ind_order });
        if (miaarrnavi) {
          for (const mianave of miaarrnavi) {
            let persistente = await NavePersistente.findByRigaColByDonatore(idapp, mianave.riga, mianave.col, 0);
            if (persistente.provvisoria) {
              fieldsvalue = {
                ind_order: -1
              };

              let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue });
              if (!!ris) {
                rimosso++;
              }
            }
          }
        }

        if (!!myuser) {
          // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          // CONTROLLARE !!!
          // ++Todo: Controllare che sia corretto che lo nascondo !!!

          // Metti campo 'delete': true su ListaIngresso
          olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: old_ind_order });
          if (!!olduseringresso) {
            let fieldsvalue = {
              deleted: true
            };
            const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false });
          }
        }

        if (!!myuser) {
          // Metti Deleted allo User
          fieldsvalue = {
            deleted: true
          };
          await User.findByIdAndUpdate(myuser.id, { $set: fieldsvalue });

        }

        // Aggiorna la Nave con il Nuovo
        fieldsvalue = {
          ind_order: myusernuovo.ind_order
        };

        const dachi = req.user.name + ' ' + req.user.surname;


        return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue })
          .then(async (rec) => {
            // tools.mylogshow(' REC TO MODIFY: ', rec);
            if (!rec) {
              return res.status(404).send();
            } else {
              if (mydata.notifBot && !!navepersistente.link_chat) {
                // Send Notification to the BOT
                let messaggio = tools.get__('SPOSTATO', req.user.lang);

                if (!!navepersistente.date_start) {
                  messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_start) + tools.ACAPO;
                }
                if (!!navepersistente.link_chat) {
                  messaggio += tools.ACAPO + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + navepersistente.link_chat + tools.ACAPO;
                }

                const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col);
                messaggio += tools.ACAPO + myplacca;

                await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio);

                await telegrambot.sendMsgTelegramToTheManagers(idapp, mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio);
                await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt);
                await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca);
              }


              // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')';
              // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,);

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

          }).catch((e) => {
            tools.mylogserr('Error patch USER: ', e);
            res.status(400).send();
          })
      }
    } else if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO) {
      // Ottieni il prossimo Numero di Tessitura
      //let num_tess = await Nave.getNextNumTess(idapp, ind_order);
      const num_tess = 1;

      /*
      let listaingr = await ListaIngresso.find({ idapp, ind_order }).sort({ num_tess: 1 });
      const trovato = listaingr.find((rec) => rec.num_tess === num_tess);
      if (trovato) {
        num_tess = listaingr.slice(-1)[0].num_tess + 2;
      }
      */

      // metti l'invitante inizialmente a Te stesso !
      const invitante_username = req.body.data.invitante_username;

      ris = await ListaIngresso.addUserInListaIngresso(idapp, username, invitante_username, myuser.lang, true, true);

      arrimbarchi = await ListaIngresso.findAllByUsername(idapp, username);
      return res.send({ code: server_constants.RIS_CODE_OK, arrimbarchi });

    } else if (mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) {

      await ListaIngresso.remove({ idapp, username, ind_order });

      return res.send({ code: server_constants.RIS_CODE_OK });

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

router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => {
//   const idapporig = req.params.idapporig;
//   const idappdest = req.params.idappdest;
//   if (!idapporig || !idappdest)
//     res.status(400).send();
//
//   const mytablesstr = ['settings', 'users', 'templemail', 'contribtype'];
//
//   try {
//     let numrectot = 0;
//     for (const table of mytablesstr) {
//       const mytable = getTableByTableName(table);
//
//       tools.mylogshow('copyfromapptoapp: ', table, mytable);
//
//       await mytable.DuplicateAllRecords(idapporig, idappdest).then((numrec) => {
//         // tools.mylogshow(' REC TO MODIFY: ', rec);
//         numrectot += numrec
//       });
//     }
//
//     res.send({ code: server_constants.RIS_CODE_OK, msg: '', numrectot });
//
//   } catch (e) {
//     tools.mylogserr('Error copyfromapptoapp: ', e);
//     res.status(400).send();
//   }
});

router.delete('/delrec/:table/:id', authenticate, async (req, res) => {
  const id = req.params.id;
  const idapp = req.user.idapp;
  const tablename = req.params.table;
  let notifBot = false;
  // const idapp = req.body.idapp;

  console.log('id', id, 'table', tablename);

  const mytable = getTableByTableName(tablename);

  const fields = { 'ALL': 1 };

  if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (tablename !== 'extralist') && !tools.ModificheConsentite(tablename, fields, id, req.user)) {
    // If without permissions, exit
    return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
  }

  let cancellato = false;

  notifBot = tools.NotifyIfDelRecord(tablename);
  let myrec = null;

  if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) {
    if (tablename === 'users') {

      let fieldsvalue = {
        deleted: true
      };

      const rec = await mytable.findByIdAndUpdate(id, { $set: fieldsvalue });
      myrec = rec;

      cancellato = true;
    }
  }

  let ris = null;

  if (!cancellato) {
    ris = await mytable.findByIdAndRemove(id).then((rec) => {
      if (!rec) {
        return res.status(404).send();
      }
      myrec = rec;

      cancellato = true;

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

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

  if (cancellato) {
    // Do extra things after deleted
    return actions.doOtherThingsAfterDeleted(tablename, myrec).then(async (ris) => {
      if (ris) {

        if (notifBot) {
          // Send Notification to the BOT
          let nomerecord = '';
          if ((tablename === 'users') || (tablename === 'extralist')) {
            nomerecord = myrec.name + ' ' + myrec.surname + ' (' + myrec.username + ')';
          }

          addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' +
            'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n';
          await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext);
        }

        tools.mylog('DELETED Others things ...');
        return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
      }
    });
  }

  res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
  return ris;

});


router.post('/duprec/:table/:id', authenticate, (req, res) => {
  const id = req.params.id;
  const tablename = req.params.table;
  // const idapp = req.body.idapp;

  console.log('id', id, 'table', tablename);

  const mytable = getTableByTableName(tablename);

  if (!req.user) {
    return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
  }

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

  return mytable.findById(id).then((mydata) => {

    const datadup = tools.CloneRecordToNew(mydata);
    const mynewrec = new mytable(datadup);

    return mynewrec.save()
      .then((rec) => {
        if (!rec) {
          return res.status(404).send();
        }

        tools.mylog('DUPLICATED ', rec);

        // Do extra things after deleted
        return actions.doOtherThingsAfterDuplicated(tablename, rec).then(({ myrec }) => {
          // ...
          mytable.findById(myrec._id).then((record) => {
            return res.send({ code: server_constants.RIS_CODE_OK, record, msg: '' });
          });

        });

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

});


function doOtherThingsAfterDeleted() {

}

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

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

  let bookedevent = [];
  let msgs = [];

  if (userId !== '0') {
    // LOGGED WITH USERID
    bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall);
  }

  // Extract all the todos of the userId only
  const eventlist = MyEvent.findAllIdApp(idapp);
  const operators = Operator.findAllIdApp(idapp);
  const wheres = Where.findAllIdApp(idapp);
  const contribtype = Contribtype.findAllIdApp(idapp);
  const paymenttype = PaymentType.findAllIdApp(idapp);
  const disciplines = Discipline.findAllIdApp(idapp);
  const settings = Settings.findAllIdApp(idapp, false);

  const permissions = Permission.findAllIdApp();

  let newstosent = Promise.resolve([]);
  let mailinglist = Promise.resolve([]);
  let mypage = MyPage.findAllIdApp(idapp);
  let calzoom = CalZoom.findAllIdApp(idapp);
  let gallery = Gallery.findAllIdApp(idapp);
  if (sall) {
    newstosent = Newstosent.findAllIdApp(idapp);
  }

  let calcstat = null;
  if (req.user)
    calcstat = User.calculateStat(idapp, req.user.username);


  return Promise.all([bookedevent, eventlist, operators, wheres, contribtype, settings, permissions, disciplines, newstosent, mailinglist, mypage, gallery, paymenttype, calcstat, calzoom])
    .then((arrdata) => {
      // console.table(arrdata);
      const myuser = req.user;
      if (myuser) {
        myuser.password = '';
        myuser._doc.calcstat = arrdata[13];
      }

      res.send({
        bookedevent: arrdata[0],
        eventlist: arrdata[1],
        operators: arrdata[2],
        wheres: arrdata[3],
        contribtype: arrdata[4],
        settings: arrdata[5],
        permissions: arrdata[6],
        disciplines: arrdata[7],
        newstosent: arrdata[8],
        mailinglist: arrdata[9],
        mypage: arrdata[10],
        gallery: arrdata[11],
        paymenttypes: arrdata[12],
        calzoom: arrdata[14],
        myuser,
      });
    })
    .catch((e) => {
      console.log(e.message);
      res.status(400).send(e);
    });

});

router.get(process.env.LINK_CHECK_UPDATES, authenticate, async (req, res) => {
  const userId = req.user._id;
  const idapp = req.query.idapp;

  // console.log("POST " + process.env.LINK_CHECK_UPDATES + " userId=" + userId);

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

  await cfgserver.find({ idapp }).then((arrcfgrec) => {

    if (!arrcfgrec)
      return res.status(404).send();

    // ++Todo: Add to Log Stat ....

    // const sall = '0';

    // msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
    last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, req.user.idapp);

    let usersList = null;

    if (req.user) {
      // If User is Admin, then send user Lists
      if (User.isAdmin(req.user.perm)) {
        // Send UsersList
        // usersList = User.getUsersList(req.user.idapp)
        usersList = null;
      }
    }

    return Promise.all([usersList, last_msgs])
      .then((arrdata) => {
        // console.table(arrdata);
        return res.send({
          cfgServer: arrcfgrec,
          usersList: arrdata[0],
          last_msgs: arrdata[1],
        });
      });

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

});

router.post('/upload_from_other_server/:dir', authenticate, (req, res) => {
  const dir = req.params.dir;
  const idapp = req.user.idapp;

  /*
    const form = new formidable.IncomingForm();

    form.parse(req);

    const client = new ftp(process.env.FTPSERVER_HOST, process.env.FTPSERVER_PORT, process.env.FTPSERVER_USER + idapp + '@associazioneshen.it', process.env.FTPSERVER_PWD + idapp, false, 134217728);

    // SSL_OP_NO_TLSv1_2 = 134217728

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

    form.uploadDir = folder + '/' + dir;
    try {

      form.on('fileBegin', async function (name, file){
        file.path = folder + '/' + file.name;
      });

      form.on('file', async function (name, file){
        try {
          // Create directory remote

          if (!!dir)
            await client.createDir(dir);

          const miofile = (dir) ? dir + ` / ` + file.name : file.name;
          console.log('Upload...');
          const ret = await client.upload(file.path, miofile, 755);
          console.log('Uploaded ' + file.name, 'status:', ret);
          if (!ret)
            res.status(400).send();
          else {
            // Delete file from local directory
            fs.unlinkSync(file.path);
            res.end();
          }
        }catch (e) {
          console.log('error', e);
          res.status(400).send();
        }
      });

      form.on('aborted', () => {
        console.error('Request aborted by the user');
        res.status(400).send();
      });

      form.on('error', (err) => {
        console.error('Error Uploading', err);
        res.status(400).send();
      });

    } catch (e) {
      console.log('Error', e)
    }
  */


});


router.post('/upload/:dir', authenticate, (req, res) => {
  const dir = req.params.dir;
  const idapp = req.user.idapp;

  // console.log('/upload dir:' + dir);

  const form = new formidable.IncomingForm();

  form.parse(req);

  form.uploadDir = folder + '/' + dir;
  try {

    form.on('fileBegin', async function (name, file) {
      file.path = folder + '/' + file.name;
    });

    form.on('file', async function (name, file) {
      try {
        console.log('Uploaded ' + file.name);
        const mydir = tools.getdirByIdApp(idapp) + '/statics/upload/' + dir;

        // Create Dir if doesn't exist:
        tools.mkdirpath(mydir);
        newname = mydir + '/' + file.name;

        console.log('move from ', file.path, 'to :', newname);

        // For local: ... resolve this... sending through the static folder...
        // res.sendFile(path.resolve(file.name));

        // Move in the folder application !
        tools.move(file.path, newname, (err) => {
          if (err)
            console.log('err:', err);
          res.end();
        });

      } catch (e) {
        console.log('error', e);
        res.status(400).send();
      }
    });

    form.on('aborted', () => {
      console.error('Request aborted by the user');
      res.status(400).send();
    });

    form.on('error', (err) => {
      console.error('Error Uploading', err);
      res.status(400).send();
    });

  } catch (e) {
    console.log('Error', e)
  }

});


router.delete('/delfile', authenticate, (req, res) => {
  const relativefile = req.query.filename;
  const idapp = req.user.idapp;

  try {

    try {
      console.log('Delete file ' + relativefile);
      // ++ Move in the folder application !
      fullpathfile = tools.getdirByIdApp(idapp) + '/' + relativefile;

      tools.delete(fullpathfile, (err) => {
        if (err) console.log('err', err);
        if (err === undefined || err.errno === -2)
          res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
      });

    } catch (e) {
      console.log('error', e);
      res.status(400).send();
    }
  } catch (e) {
    console.log('Error', e)
  }

});


module.exports = router;
