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

const { User } = require('../models/user');
const { Nave } = require('../models/nave');
const { NavePersistente } = require('../models/navepersistente');
const { ListaIngresso } = require('../models/listaingresso');
// const { ExtraList } = require('../models/extralist');
const { ObjectID } = require('mongodb');

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

const { Settings } = require('../models/settings');

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

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

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

const _ = require('lodash');

const reg = require('../reg/registration');

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

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

function existSubScribe(userId, access, browser) {
  return Subscription.findOne({ userId, access, browser })
    .then(itemsub => {
      return itemsub
    })
    .catch(err => {
      return null
    })

}

function getMobileComplete(user) {
  let str = user.profile.intcode_cell + user.profile.cell;
  str = str.replace(/\s+/g, '');
  // str = str.replace(/.+/g, '');
  // str = str.replace(/-+/g, '');

  return str
}


// POST /users
router.post('/', async (req, res) => {
  tools.mylog("POST /users");
  const body = _.pick(req.body, ['email', 'password', 'username', 'name', 'surname', 'idapp', 'keyappid', 'lang', 'profile', 'aportador_solidario']);
  body.email = body.email.toLowerCase();

  const user = new User(body);

  // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp);

  user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
  user.verified_email = false;
  user.ipaddr = tools.getiPAddressUser(req);
  user.lasttimeonline = new Date();
  user.date_reg = new Date();
  user.aportador_iniziale = user.aportador_solidario;
  if (user.idapp === tools.AYNI) {
    user.profile.paymenttypes = ['paypal'];
  }
  // user.perm = 3;
  if (tools.testing()) {
    user.verified_email = true;
  }

  // if (user.profile.intcode_cell) {
  //   if (user.profile.cell.substring(0, user.profile.intcode_cell.length) === user.profile.intcode_cell) {
  //     user.profile.cell = user.profile.cell.substring(user.profile.intcode_cell.length)
  //   }
  // }
  let exit;

  // Check if already esist email or username
  exit = await User.findByUsername(user.idapp, user.username).then((useralreadyexist) => {
    if (useralreadyexist) {
      res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST, msg: '' });
      return 1;
    }

  });

  if (exit === 1)
    return;

  exit = await User.findByEmail(user.idapp, user.email)
    .then((useralreadyexist) => {
      if (useralreadyexist) {
        res.status(400).send({ code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST, msg: '' });
        return 1;
      }

    });

  if (exit === 1)
    return;

  let recuser = null;

  recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name, user.surname);
  if (recuser) {
    console.log('UTENTE GIA ESISTENTE:\n');
    console.log(user);
    // User already registered!
    res.status(400).send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' });
    return 1;
  }

  let recextra = null;

  // recextra = await ExtraList.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name, user.surname);
  // let nomeaportador_corretto = "";
  // if (recextra) {
  //   nomeaportador_corretto = recextra.aportador_solidario_name_surname;
  //   if (nomeaportador_corretto === '')
  //     nomeaportador_corretto = recextra.aportador_solidario_originale_name_surname;
  // }

  const lastuser = await User.getLastUser(user.idapp);
  // const lastextra = await ExtraList.getLastUser(user.idapp);
  let lastindorder = 0;

  if (lastuser) {
    lastindorder = lastuser.ind_order;
  }
  //if (lastextra) {
  //  if (lastextra.ind_order > lastindorder)
  //    lastindorder = lastextra.ind_order;
  //}

  if (lastindorder > 0)
    user.ind_order = lastindorder + 1;

  const numero = user.name.slice(-1);
  if ((numero === '2') || (numero === '3') || (numero === '4') || (numero === '5') || (numero === '6')) {
    recorig = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name.slice(0, -1), user.surname);
    if (!!recorig) {
      user.profile.teleg_id = recorig.profile.teleg_id;
      user.profile.saw_zoom_presentation = recorig.profile.saw_zoom_presentation;
      user.profile.saw_and_accepted = recorig.profile.saw_and_accepted;
      user.profile.my_dream = recorig.profile.my_dream;
      user.profile.email_paypal = recorig.profile.email_paypal;
      user.profile.paymenttypes = recorig.profile.paymenttypes;
      let msgseconda = '!!! REGISTRATA ';
      if (numero === '2')
        msgseconda += 'SECONDA';
      else if (numero === '3')
        msgseconda += 'TERZA';
      else if (numero === '4')
        msgseconda += 'QUARTA';

      msgseconda += ' UTENZA di ' + recorig.name + ' ' + recorig.surname + ' (' + recorig.username + ') : ' + user.name + ' ' + user.surname + ' (' + user.username + ') ';
      await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msgseconda);
    }
  }

  namesurname_aportador_reg = await User.getNameSurnameByUsername(user.idapp, user.aportador_solidario);

  if (recextra && namesurname_aportador_reg !== '' && namesurname_aportador_reg !== nomeaportador_corretto) {
    // Si sta tentando di registrare una persona sotto che non corrisponde!
    let msg = 'L\'utente ' + user.name + ' ' + user.surname + ' si sta registrando con il link di ' + user.aportador_solidario + ' (' + namesurname_aportador_reg + ') ' +
      'invece è assegnato a ' + nomeaportador_corretto;

    await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
    res.status(400).send({ code: server_constants.RIS_CODE_USER_NOT_THIS_APORTADOR, msg: '' });
    return 1;
  }

  let already_registered = (recextra || user.aportador_solidario === tools.APORTADOR_NONE) && (user.idapp === tools.AYNI);


  // Check if is an other people aportador_solidario

  if (already_registered) {
    // Check in the extraList if is present!
    if (!recextra) {
      const msg = 'Utente non trovato: ' + user.name + ' ' + user.surname + ' ' + user.profile.nationality + ' ' + user.profile.cell + ' email: ' + user.email + ' username: ' + user.username;
      console.log('Utente non trovato; ', msg);
      await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
      res.status(400).send({
        code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND,
        msg: 'Controlla se il numero ' + user.profile.cell + ' è corretto.'
      });
      return 1;
    } else {
      user.ind_order = recextra.ind_order;
      user.date_reg = recextra.date_reg;
      if (recextra.aportador_solidario_name_surname)
        user.aportador_solidario_nome_completo = recextra.aportador_solidario_name_surname;
      else
        user.aportador_solidario_nome_completo = recextra.aportador_solidario_originale_name_surname;

      user.aportador_solidario_ind_order = recextra.aportador_solidario_ind_order;

      user.note = recextra.note;

      if (recextra.is_staff) {
        user.perm = shared_consts.Permissions.Manager;
      }
      if (recextra.username === 'paoloar77') {
        user.perm = shared_consts.Permissions.Manager + shared_consts.Permissions.Admin;
      }

      // const useraportador = await ExtraList.findByIndOrder(user.idapp, user.aportador_solidario_ind_order);
      // if (useraportador)
      //   user.aportador_solidario = useraportador.username;
    }

  }

  return await user.save()
    .then(async () => {
      return await User.findByUsername(user.idapp, user.username, false)
        .then((usertrovato) => {

          // tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato);
          if (usertrovato !== null) {
            return user.generateAuthToken(req);
          } else {
            res.status(400).send();
            return 0;
          }
        })
        .then(async (token) => {
          // tools.mylog("passo il TOKEN: ", token);

          if (recextra) {
            recextra.registered = true;
            recextra.username = user.username;
            await recextra.save();

            await User.fixUsername(user.idapp, user.ind_order, user.username);
          }
          return token;
        })
        .then(async (token) => {

          // tools.mylog("LINKREG = " + user.linkreg);
          // Invia un'email all'utente
          // tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON);
          console.log('res.locale', res.locale);
          if (!tools.testing()) {
            await sendemail.sendEmail_Registration(user.lang, user.email, user, user.idapp, user.linkreg);
          }
          res.header('x-auth', token).send(user);
          return true;
        });
    }).catch((e) => {
      res.status(400).send(e);
    })
});

router.get('/:idapp/:username', async (req, res) => {
  var username = req.params.username;
  const idapp = req.params.idapp;

  // if (username === 'pippo') {
  //   return res.status(200).send();
  // }

  await User.findByUsername(idapp, username, false).then((user) => {
    if (!user) {
      return res.status(404).send();
    }
    res.status(200).send();
  }).catch((e) => {
    res.status(400).send();
  });
});

router.patch('/:id', authenticate, (req, res) => {
  const id = req.params.id;
  const body = _.pick(req.body.user, shared_consts.fieldsUserToChange());

  tools.mylogshow('PATCH USER: ', id);

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

  User.findByIdAndUpdate(id, { $set: body }).then((user) => {
    tools.mylogshow(' USER TO MODIFY: ', user);
    if (!user) {
      return res.status(404).send();
    } else {
      res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
    }

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


router.post('/login', (req, res) => {
  var body = _.pick(req.body, ['username', 'password', 'idapp', 'keyappid', 'lang']);
  var user = new User(body);
  // const subs = _.pick(req.body, ['subs']);

  // tools.mylog("LOGIN: username: " + user.username + " pwd = " + user.password);

  // tools.mylog("user REC:", user);

  if (body.keyappid !== process.env.KEY_APP_ID)
    return res.status(400).send();

  let resalreadysent = false;

  User.findByCredentials(user.idapp, user.username, user.password)
    .then(async (user) => {
      // tools.mylog("CREDENZIALI ! ");
      if (!user) {
        await tools.snooze(3000);
        const msg = "Tentativo di Login ERRATO [" + body.username + ' , ' + body.password + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
        tools.mylogshow(msg);
        // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
        res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
      }
      return user
    })
    .then(user => {
      if (user) {
        return user.generateAuthToken(req).then((token) => {
          var usertosend = User();

          shared_consts.fieldsUserToChange().forEach((field) => {
            usertosend[field] = user[field]
          });

          // usertosend._id = user._id.toHexString();
          // if (!User.isAdmin(req.user)) {
          //   usertosend.ipaddr = user.ipaddr;
          // }

          // tools.mylog("user.verified_email:" + user.verified_email);
          // tools.mylog("usertosend.userId", usertosend.userId);

          return { usertosend, token }

        })
          .then((myris) => {
            const access = 'auth';
            const browser = req.get('User-Agent');

            // Check if already exist Subscribe
            return existSubScribe(myris.usertosend._id, access, browser).then(subscribe => {
              return (subscribe !== null)
            }).then(subsExistonDb => {
              return { usertosend: myris.usertosend, token: myris.token, subsExistonDb }
            }).catch(err => {
              return { usertosend: myris.usertosend, token: myris.token, subsExistonDb: false }
            })
          }).then(myris => {
            // console.log('res', myris.token, myris.usertosend);

            // SEND TOKEN AND CODE RESULT
            res.header('x-auth', myris.token).send({
              usertosend: myris.usertosend,
              code: server_constants.RIS_CODE_OK,
              subsExistonDb: myris.subsExistonDb
            });

            // tools.mylog("TROVATOOO!");

            // tools.mylog('FINE LOGIN')
          });
      }
    })
    .catch((e) => {
      tools.mylog("ERRORE IN LOGIN: " + e);
      if (!resalreadysent)
        res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
    });
});

router.delete('/me/token', authenticate, (req, res) => {
  // tools.mylog("TOKENREM = " + req.token);
  req.user.removeToken(req.token).then(() => {
    res.status(200).send();
  }, () => {
    res.status(400).send();
  });
});

router.post('/setperm', authenticate, (req, res) => {
  const body = _.pick(req.body, ['idapp', 'username', 'perm']);
  tools.mylog("SETPERM = " + req.token);

  User.setPermissionsById(res.user._id, body).then(() => {
    res.status(200).send();
  }, () => {
    res.status(400).send();
  });
});

router.post('/import_extralist', async (req, res) => {

  const strdata = req.body.strdata;
  idapp = req.body.idapp;
  locale = req.body.locale;

  // const ris = await ExtraList.ImportData(locale, idapp, strdata);
  console.log('ris', ris);

  res.send(ris);
});

router.post('/dbop', authenticate, async (req, res) => {

    const mydata = req.body.mydata;
    idapp = req.body.idapp;
    locale = req.body.locale;

    let ris = await User.DbOp(idapp, mydata);

    let mystr = '';

    try {

      if (mydata.dbop === 'creaNavi') {
        const num = await Nave.generaNave(idapp, mydata);
        ris = { num };
      } else if (mydata.dbop === 'delNavi') {
        await Nave.setRiga(idapp, 1);
        await Nave.setCol(idapp, 1);
        const num = await Nave.remove({ idapp });
        ris = { num };
        // } else if (mydata.dbop === 'delNaviNoStarted') {
        //   await Nave.setRiga(idapp, 1);
        //   await Nave.setCol(idapp, 1);
        //   const num = await Nave.remove({ idapp, date_start: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 24 * 3) } });
        //   ris = { num };
      } else if (mydata.dbop === 'delNaviProvvisorie') {

        let num = 0;

        const arrnavi = await Nave.find({ idapp });

        for (const nave of arrnavi) {
          let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0);
          if (!!persistente) {
            if (persistente.provvisoria) {
              let ris = await Nave.remove({ _id: nave._id });
              if (!!ris) {
                num++;
              }
            }
          }
        }

        // Pulisci gli added se era stato cancellato dalla nave
        await Nave.pulisciNonPresenzeInNave(idapp);

        const data = await Nave.getLastRigaCol(idapp);
        await Nave.setRiga(idapp, data.riga);
        await Nave.setCol(idapp, data.col + 1);

        ris = { num };
      } else if (mydata.dbop === 'visuListaNave') {
        mystr = await Nave.showListaOrd(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'visuStat') {
        ris = await User.visuUtentiNonInNavi(idapp);
      } else if (mydata.dbop === 'pulisciNonPresenzeInNave') {
        mystr = await Nave.pulisciNonPresenzeInNave(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'checkInserimentiUtentiInNave') {
        mystr = await Nave.checkIfDevoAggiungereInNave(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'visuListaIngresso') {
        mystr = await ListaIngresso.showListaOrd(idapp, false);
        ris = { mystr };
      } else if (mydata.dbop === 'visuListaIngressoNuovi') {
        mystr = await ListaIngresso.showListaOrd(idapp, true);
        ris = { mystr };
      } else if (mydata.dbop === 'visuNaviUtentiEliminati') {
        ris = await Nave.visuNaviUtentiEliminati(idapp);
      } else if (mydata.dbop === 'creaTessituraeConv') {
        ris = await ListaIngresso.creaTessituraeConv(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') {
        let num = 0;

        const arrnavitess = await Nave.find({idapp, num_tess: { $gte: 3 } });

        for (const recnave of arrnavitess) {
          if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) {
            const ind_order = recnave.ind_order;

            // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio:
            const arringr = await ListaIngresso.find({idapp, ind_order});
            let dafare = true;
            if (arringr.length > 0) {
              const arringrtest = await ListaIngresso.find({idapp, ind_order}).distinct('num_tess');
              if (arringr.length !== arringrtest.length){
                dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto!
              }
            }
            if (dafare) {
              const user = await User.findByOldOrder(idapp, ind_order);

              if (!!user) {
                let note = recnave.num_tess;
                // Crea record ListaIngresso
                const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, note, true);

                const fieldsvalue = {
                  ind_order: newrecingr.ind_order,
                  num_tess: 1,
                };

                // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1
                await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false });

                num++;
              }
            }
          }
        }

        ris = { num };

      } else if (mydata.dbop === 'initListaIngresso') {
        // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } });

        const num = await ListaIngresso.updateMany({ idapp }, { $set: { added: false } });

        ris = { num };
      } else if (mydata.dbop === 'ImpostaATuttiPaypal') {
        const listautenti = await User.find({ idapp });
        let num = 0;
        for (let rec of listautenti) {
          if (!rec._doc.profile.paymenttypes.includes('paypal')) {
            rec._doc.profile.paymenttypes = [...rec._doc.profile.paymenttypes, 'paypal'];
            const user = await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.paymenttypes': rec._doc.profile.paymenttypes } });
            // await rec.save();
            num++;
          }
          // const num = await User.f({ idapp }, { $set: { 'profile: false } });
        }


        ris = { num };
      } else if (mydata.dbop === 'numtessUno') {
        const listanavi = await ListaIngresso.find({ idapp });
        let num = 0;
        for (let rec of listanavi) {
          if (!rec._doc.num_tess) {
            rec._doc.num_tess = 1;
            const risu = await ListaIngresso.findOneAndUpdate({ _id: rec._id }, { $set: { num_tess: rec._doc.num_tess } }, { new: false });
            // await rec.save();
            if (!!risu)
              num++;
          }
          // const num = await User.f({ idapp }, { $set: { 'profile: false } });
        }


        ris = { num };
      } else if (mydata.dbop === 'Corregginumtess') {
        const listanavi = await Nave.find({ idapp });
        let num = 0;
        for (let rec of listanavi) {
          const myarrrec = await Nave.find({ idapp, ind_order: rec.ind_order }).sort({ riga: 1, col: 1 });
          let indextess = 1;
          for (let ind = 0; ind < myarrrec.length; ind++) {
            if (myarrrec[ind].num_tess !== indextess && myarrrec[ind].num_tess === 1) {
              myarrrec[ind].num_tess = indextess;
              const risu = await Nave.findOneAndUpdate({ _id: myarrrec[ind]._id }, { $set: { num_tess: myarrrec[ind].num_tess } }, { new: false });
              num++;
            }
            indextess++;
          }
        }

        ris = { num };
        /*
        }

        else if (mydata.dbop === 'CreaNaviPersistenti') {
          const listanavi = await Nave.find({ idapp }).sort({riga: 1, col: 1});

          let params = {
            idapp
          };

          let num = 0;
          for (let rec of listanavi) {
            let mypos = {
              idapp,
              riga: rec.riga,
              col: rec.col,
              numup: 3
            };
            tools.getRigaColByPosUp(mypos);
            let persistente = await NavePersistente.findByRigaCol(idapp, mypos.riga, mypos.col, 0);
            if (!persistente) {

              params.date_start = rec.date_start;
              params.date_gift_chat_open = rec.date_gift_chat_open;
              params.riga = mypos.riga;
              params.col = mypos.col;
              if (rec.riga > 3) {
                params.riga1don = rec.riga;
                params.col1don = rec.col;
              } else {
                params.riga1don = rec.riga;
                params.col1don = rec.col;
              }
              if (params.riga > 0) {
                await NavePersistente.addRecordNavePersistenteByParams(params);
                num++;
              }
            }
          }

          ris = { num }; */
      } else if (mydata.dbop === 'CorreggiDataGiftChat') {
        const listanavi = await NavePersistente.find({ idapp });
        let num = 0;
        for (let rec of listanavi) {
          const fieldsvalue = {
            date_gift_chat_open: tools.AddDate(rec.date_start, -7)
          };
          const risu = await NavePersistente.findOneAndUpdate({ _id: rec._id }, { $set: fieldsvalue }, { new: false });
          if (!!risu) {
            num++;
          }
        }

        ris = { num };
      } else if (mydata.dbop === 'creaUtentiTest') {

        let num = 0;
        lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1);
        let last = 1;
        if (lastrec) {
          last = lastrec[0].ind_order;
        }
        if (!last) {
          last = 1;
        }

        for (let ind = 0; ind < 100; ind++) {
          let myuser = new User();
          myuser._id = new ObjectID();
          myuser.ind_order = last + ind + 1;
          myuser.idapp = idapp;
          myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG";
          myuser.lang = 'it';
          myuser.email = "miaemail@email.it";
          myuser.name = 'U' + myuser.ind_order;
          myuser.surname = 'Ar' + myuser.ind_order;
          myuser.verified_email = true;
          if (myuser.ind_order < 2)
            myuser.perm = "3";
          myuser.username = "Userna_" + myuser.name;
          myuser.profile.special_req = true;
          myuser.profile.nationality = 'IT';
          await myuser.save();
          num++;
        }

        ris = { num };
      } else if (mydata.dbop === 'visuPlacca') {

        mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' +
          'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7)  +'\n' +
          'AUGURI ALLA NUOVA SOGNATRICE !!!\n' +
          '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨';

        const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');

        for (let ind = 0; ind < 8; ind++) {
          mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false);
          mystr += tools.ACAPO;
          if (visu_nave_Bot && ind === 3) {
            await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
            mystr = '';
          }
        }

        if (visu_nave_Bot)
          await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);

        ris = { mystr };

        /*const rec = {};
        const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col), false, rec);

        telegrambot.sendMsgTelegramToTheAdmin(idapp, placca);

        ris = { placca };*/
      } else if (mydata.dbop === 'visuNave') {
        mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col));

        const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');
        if (visu_nave_Bot)
          telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);

        ris = { mystr };
      } else if (mydata.dbop === 'getnavibyuser') {

        let arrnavi = null;

        const user = await User.getUserShortDataByUsername(idapp, mydata.username);
        if (user) {
          arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username);

          for (let mynave of arrnavi) {
            mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col);
          }

        }

        ris = { data: arrnavi };
      }


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

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


module.exports = router;
