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

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

// const { Nave } = require('../models/nave');
const Hours = require('../models/hours');
//const { NavePersistente } = require('../models/navepersistente');
//const { ListaIngresso } = require('../models/listaingresso');
//const { Graduatoria } = require('../models/graduatoria');
// const { ExtraList } = require('../models/extralist');
const { ObjectID } = require('mongodb');

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

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

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

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, authenticate_noerror } = require('../middleware/authenticate');


const Cart = require('../models/cart');
const CartClass = require('../modules/Cart');
const Product = require('../models/product');
const Variant = require('../models/variant');
const TypedError = require('../modules/ErrorHandler');

const { MyGroup } = require('../models/mygroup');
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');

const mongoose = require('mongoose').set('debug', false);

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

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

  const user = await User.findOne({
    idapp: 1,
    username: 'paoloar77',
  });

  await sendemail.sendEmail_Registration(user.lang, user.email, user,
    user.idapp, user.linkreg);

});

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

  const user = new User(body);
  user.ipaddr = tools.getiPAddressUser(req);

  user.email = user.email.trim();
  user.username = user.username.trim();
  user.name = user.name.trim();
  user.surname = user.surname.trim();

  if ((user.aportador_solidario === 'tuo_username') || (user.aportador_solidario === '{username}')) {
    user.aportador_solidario = 'paoloar77';
  }

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

  if (!tools.isAlphaNumericAndSpecialCharacter(body.username) ||
    body.email.length < 6 ||
    body.username.length < 6 || body.password.length < 6) {
    await tools.snooze(5000);
    console.log('Username non valido in Registrazione: ' + body.username);
    res.status(400).
      send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' });
    return 1;
  }

  if (tools.blockwords(body.username) || tools.blockwords(body.name) ||
    tools.blockwords(body.surname)) {
    // tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname);
    await tools.snooze(5000);
    return res.status(404).send();
  }

  user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
  user.verified_email = false;
  user.lasttimeonline = new Date();
  user.date_reg = new Date();
  user.aportador_iniziale = user.aportador_solidario;

  let regexpire = req.body['regexpire'];
  let nonchiedereverifica = false;
  if (regexpire) {
    nonchiedereverifica = await User.getifRegTokenIsValid(body.idapp, regexpire);
  }

  if (!nonchiedereverifica)
    regexpire = '';

  if (!tools.getAskToVerifyReg(body.idapp) || nonchiedereverifica) {
    // Se non devo chiedere di verificare all'Invitato, allora lo verifico direttamente
    user.verified_by_aportador = true;
  }

  /* if (user.idapp === tools.AYNI) {
    user.profile.paymenttypes = ['paypal'];
  } */

  // Controlla se anche l'ultimo record era dallo stesso IP:
  const lastrec = await User.getLastRec(body.idapp);
  if (!!lastrec) {
    if (process.env.LOCALE !== '1') {
      if (lastrec.ipaddr === user.ipaddr) {
        // Se l'ha fatto troppo ravvicinato
        if (lastrec.date_reg) {
          let ris = tools.isdiffSecDateLess(lastrec.date_reg, 5);
          if (ris) {
            tools.writeIPToBan(
              user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' +
              user.surname);
            await tools.snooze(10000);
            res.status(400).
              send({ code: server_constants.RIS_CODE_BANIP, msg: '' });
            return 1;
          }
        }
      }
    }
  }

  // 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;

  let utentenonancoraVerificato = false;

  const trovarec = await User.findByCredentials(user.idapp, user.username, user.password, true);

  // Check if already esist email or username
  exit = await User.findByUsername(user.idapp, user.username).
    then((useralreadyexist) => {
      if (useralreadyexist) {

        if (tools.getAskToVerifyReg(useralreadyexist.idapp)) {
          if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) {
            if (trovarec) {
              utentenonancoraVerificato = true;
            }
          }

        }

        if (!utentenonancoraVerificato) {
          res.status(400).
            send({
              code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST,
              msg: '',
            });
          return 1;
        }
      }

    });

  if (!utentenonancoraVerificato) {

    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 && user.name !== '' && user.surname !== '' &&
      user.profile.cell !== '') {
      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;

  user.aportador_solidario = user.aportador_solidario.trim();

  const id_aportador = await User.getIdByUsername(user.idapp, user.aportador_solidario);
  if (id_aportador) {
    user.aportador_solidario = await User.getRealUsernameByUsername(user.idapp, user.aportador_solidario);
  }

  if (!id_aportador && tools.getAskToVerifyReg(body.idapp)) {
    // Si sta tentando di registrare una persona sotto che non corrisponde!
    let msg = 'Il link di registrazione non sembra risultare valido.<br>invitante: ' +
      user.aportador_solidario + '<br>username: ' + user.username;

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

  if (utentenonancoraVerificato) {
    if (id_aportador) {
      // Se mi sono registrato ma l'invitante non mi abilita, allora il posso registrarmi nuovamente, con lo stesso username e password,
      // con un'altro link di un'altro invitante !
      await User.setaportador_solidario(user.idapp, user.username,
        user.aportador_solidario);

      const myuser = await User.findOne({ _id: trovarec._id });
      if (myuser) {

        await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);

        const token = await myuser.generateAuthToken(req);
        res.header('x-auth', token).send(myuser);
        return true;
      }
    }
  }

  // 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!
    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;
  } */

  return user.save().then(async () => {
    return 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);

        await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire);

        // 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) => {
    console.error(e.message);
    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, true).then((user) => {
    if (!user) {
      return res.status(404).send();
    }
    // console.log('TROVATO!')
    return res.status(200).send();
  }).catch((e) => {
    return 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('/receiveris', authenticate, (req, res) => {
  const username = req.user ? req.user.username : '';
  const groupname = req.body.groupname;
  const idapp = req.body.idapp;

  try {
    if (!username)
      return res.send({ code: server_constants.RIS_CODE_ERR });

    if (groupname) {
      return MyGroup.setReceiveRisGroup(idapp, groupname)
        .then(risult => {
          res.send({ code: server_constants.RIS_CODE_OK });
        }).catch((err) => {
          tools.mylog('ERRORE IN receiveris: ' + err.message);
          res.status(400).send();
        });
    } else if (username) {
      return User.setReceiveRis(idapp, username)
        .then(risult => {
          res.send({ code: server_constants.RIS_CODE_OK });
        }).catch((err) => {
          tools.mylog('ERRORE IN receiveris: ' + err.message);
          res.status(400).send();
        });
    }
  } catch (e) {
    res.status(400).send();

  };
});

router.post('/profile', authenticate_noerror, (req, res) => {
  const usernameOrig = req.user ? req.user.username : '';
  const perm = req.user ? req.user.perm : tools.Perm.PERM_NONE;
  const username = req.body['username'];
  const idapp = req.body.idapp;
  const locale = req.body.locale;

  //++Todo: controlla che tipo di dati ha il permesso di leggere

  try {
    // Check if ìs a Notif to read
    const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
    SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);

    return User.getUserProfileByUsername(idapp, username, usernameOrig,
      false, perm).
      then((ris) => {

        return User.getFriendsByUsername(idapp, usernameOrig).
          then(async (friends) => {
            if (username === usernameOrig) {
              const userprofile = await User.getExtraInfoByUsername(idapp, username);
              ris.profile = userprofile;
            }

            return { ris, friends };

          }).then(tot => {
            return res.send({ user: tot.ris, friends: tot.friends });
          });

      }).catch((e) => {
        tools.mylog('ERRORE IN Profile: ' + e.message);
        res.status(400).send();
      });
  } catch (e) {
    tools.mylogserr('Error profile: ', e);
    res.status(400).send();
  }

});

router.post('/panel', authenticate, async (req, res) => {
  const username = req.body['username'];
  idapp = req.body.idapp;
  locale = req.body.locale;

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

  try {
    const myuser = await User.findOne({ idapp, username },
      {
        username: 1,
        name: 1,
        surname: 1,
        email: 1,
        verified_by_aportador: 1,
        aportador_solidario: 1,
        lasttimeonline: 1,
        deleted: 1,
        sospeso: 1,
        blocked: 1,
        reported: 1,
        username_who_report: 1,
        date_report: 1,
        profile: 1,
      }).lean();
    if (!!myuser) {
      res.send(myuser);
    } else {
      tools.mylog('ERRORE IN panel: ');
      res.status(400).send();
    }
  } catch (e) {
    tools.mylogserr('Error profile: ', e);
    res.status(400).send();
  }

});

router.post('/notifs', authenticate, async (req, res) => {
  /* const notifs = req.body['notifs'];
  idapp = req.body.idapp;
  locale = req.body.locale;
 
  const myuser = req.user;
  if (!myuser) {
    return res.status(404).
        send({code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: ''});
  }
 
  try {
    if (!!myuser) {
      if (tools.isArray(notifs) && notifs.length >= 0) {
        myuser.profile.notifs = notifs;
        myuser.save();
        return res.send({code: server_constants.RIS_CODE_OK, msg: ''});
      }
    }
    return res.send({code: server_constants.RIS_CODE_OK, msg: ''});
  } catch (e) {
    tools.mylogserr('Error profile: ', 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("LOG: u: " + user.username + " p:" + 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);
        tools.writeErrorLog(msg);
        // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
        res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
      }
      return user;
    }).
    then(user => {
      // console.log('Lgn-Ok');
      if (user) {
        return user.generateAuthToken(req).then((token) => {
          var usertosend = new 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 => {
              // console.log('ESEGUITO OK')
              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
          return 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) => {
      console.error('ERRORE IN LOGIN: ' + e.message);
      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(req.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('/friends', authenticate, (req, res) => {
  const username = req.user.username;
  idapp = req.body.idapp;
  locale = req.body.locale;

  return User.getFriendsByUsername(idapp, username).then((ris) => {
    res.send(ris);
  }).catch((e) => {
    tools.mylog('ERRORE IN Profile: ' + e.message);
    res.status(400).send();
  });

});

router.post('/groups', authenticate, (req, res) => {
  const username = req.user.username;
  idapp = req.body.idapp;
  locale = req.body.locale;

  return MyGroup.getGroupsByUsername(idapp, username, req).then((ris) => {
    res.send(ris);
  }).catch((e) => {
    tools.mylog('ERRORE IN groups: ' + e.message);
    res.status(400).send();
  });

});

router.post('/circuits', authenticate, (req, res) => {
  const username = req.user.username;
  idapp = req.body.idapp;
  locale = req.body.locale;

  return Circuit.getCircuitsByUsername(idapp, username, req.user).then((ris) => {
    res.send(ris);
  }).catch((e) => {
    tools.mylog('ERRORE IN circuits: ' + e.message);
    res.status(400).send();
  });

});

router.post('/updatesaldo', authenticate, async (req, res) => {
  const username = req.user.username;
  idapp = req.body.idapp;
  locale = req.body.locale;
  circuitId = req.body.circuitId;
  groupname = req.body.groupname;
  const lastdr = req.body['lastdr'] ? req.body['lastdr'] : '';

  try {
    const userprofile = await User.getExtraInfoByUsername(idapp, username);
    let ris = {
      userprofile
    }

    const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER);
    
    ris.arrrecnotif = arrrecnotif;

    return res.send({ ris });

  } catch (e) {
    tools.mylog('ERRORE IN updatesaldo: ' + e);
    res.status(400).send();
  };

});

router.post('/friends/cmd', authenticate, async (req, res) => {
  const usernameLogged = req.user.username;
  const idapp = req.body.idapp;
  const locale = req.body.locale;
  let usernameOrig = req.body.usernameOrig;
  let usernameDest = req.body.usernameDest;
  const cmd = req.body.cmd;
  const value = req.body.value;

  if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) {
    // If without permissions, exit
    if ((usernameOrig !== usernameLogged) && (
      (usernameDest !== usernameLogged) &&
      ((cmd === shared_consts.FRIENDSCMD.SETFRIEND) ||
        (cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE))

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

  usernameOrig = await User.getRealUsernameByUsername(idapp, usernameOrig);
  usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest);

  return User.setFriendsCmd(req, idapp, usernameOrig, usernameDest, cmd, value).
    then((ris) => {
      res.send(ris);
    }).
    catch((e) => {
      tools.mylog('ERRORE IN Friends/cmd: ' + e.message);
      res.status(400).send();
    });

});

router.post('/sendcmd', authenticate, async (req, res) => {
  const usernameLogged = req.user.username;
  const idapp = req.body.idapp;
  const locale = req.body.locale;
  let usernameOrig = req.body.usernameOrig;
  let usernameDest = req.body.usernameDest;
  const cmd = req.body.cmd;
  const value = req.body.value;

  usernameOrig = await User.getRealUsernameByUsername(idapp, usernameOrig);
  usernameDest = await User.getRealUsernameByUsername(idapp, usernameDest);

  return User.sendCmd(req, idapp, usernameOrig, usernameDest, cmd, value).
    then((ris) => {
      res.send(ris);
    }).
    catch((e) => {
      tools.mylog('ERRORE IN sendcmd: ' + e.message);
      res.status(400).send();
    });

});

router.post('/groups/cmd', authenticate, (req, res) => {
  const usernameLogged = req.user.username;
  const idapp = req.body.idapp;
  const locale = req.body.locale;
  const usernameOrig = req.body.usernameOrig;
  const groupnameDest = req.body.groupnameDest;
  const cmd = req.body.cmd;
  const value = req.body.value;

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

  return User.setGroupsCmd(idapp, usernameOrig, groupnameDest, cmd, value, usernameLogged).
    then((ris) => {
      res.send(ris);
    }).
    catch((e) => {
      tools.mylog('ERRORE IN groups/cmd: ' + e.message);
      res.status(400).send();
    });

});

router.post('/circuits/cmd', authenticate, async (req, res) => {
  const usernameLogged = req.user.username;
  const idapp = req.body.idapp;
  const locale = req.body.locale;
  const usernameOrig = req.body.usernameOrig;
  const circuitname = req.body.circuitname;
  const cmd = req.body.cmd;
  const value = req.body.value;
  const extrarec = req.body.extrarec;


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

  return await User.setCircuitCmd(idapp, usernameOrig, circuitname, cmd, value, usernameLogged, extrarec).
    then(async (ris) => {

      // Check if ìs a Notif to read
      if (extrarec && extrarec.hasOwnProperty('idnotif')) {
        const idnotif = extrarec['idnotif'] ? extrarec['idnotif'] : '';
        await SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
      }

      return res.send(ris);
    }).
    catch((e) => {
      tools.mylog('ERRORE IN circuits/cmd: ' + e.message);
      res.status(400).send();
    });

});

async function eseguiDbOp(idapp, mydata, locale, req, res) {

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

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

  const globalTables = require('../tools/globalTables');
  const { Reaction } = require('../models/reaction');

  let mystr = '';

  try {

    if (mydata.dbop === '') {

      // } else if (mydata.dbop === 'rigeneraTutto') {
      //   await ListaIngresso.Esegui_CronTab(idapp, mydata);
    } else if (mydata.dbop === 'visuStat') {
      // ris = await User.visuUtentiNonInNavi(idapp);
      //} else if (mydata.dbop === 'creaNavi') {
      //  const num = await Nave.generaNave(idapp, mydata, false);
      //  ris = { num };
      //} else if (mydata.dbop === 'CreaNaviPersistenti') {
      //   const num = await Nave.generaNave(idapp, mydata, true);
      //  ris = { num };
      /*} else if (mydata.dbop === 'delNavi') {
        await Nave.setRiga(idapp, 1);
        await Nave.setCol(idapp, 1);
        const num = await Nave.deleteOne({ 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') {
 
        ris = await Nave.delNaviProvvisorie(idapp);
 
      } else if (mydata.dbop === 'visuListaNave') {
        mystr = await Nave.showListaOrd(idapp);
        ris = { mystr };
      } 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 === 'GeneraGraduatoria') {
        mystr = await ListaIngresso.GeneraGraduatoria(idapp, true);
        ris = { mystr };
      } else if (mydata.dbop === 'AggiornaIndiceGraduatoria') {
        mystr = await Graduatoria.AggiornaIndiceGraduatoria(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'visuNaviUtentiEliminati') {
        ris = await Nave.visuNaviUtentiEliminati(idapp);
      } else if (mydata.dbop === 'convSubAccount') {
        ris = await User.convSubAccount(idapp);
      } else if (mydata.dbop === 'flagUtentiNaviNonPresenti') {
        ris = await User.flagUtentiNaviNonPresenti(idapp);
      } else if (mydata.dbop === 'generaFlotte') {
        ris = await NavePersistente.generaFlotte(idapp);
      } else if (mydata.dbop === 'mettiSognoePaypal') {
        ris = await User.mettiSognoePaypal(idapp, true);
      } else if (mydata.dbop === 'mettiSognoePaypalView') {
        ris = await User.mettiSognoePaypal(idapp, false);
      } else if (mydata.dbop === 'addNavePerUtentiNaviNonPresenti') {
        ris = await User.addNavePerUtentiNaviNonPresenti(idapp);
      } else if (mydata.dbop === 'creaTessituraeConv') {
        ris = await ListaIngresso.creaTessituraeConv(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'eliminaListeIngressoNascoste') {
        ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp);
        ris = { mystr };
      } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') {
        ris = await ListaIngresso.RendiVisibileIrecordNascosti(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);
              const user = await User.findByIndOrder(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, '', 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++;
              }
            }
          }
        }
 
 
        const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 });
 
        for (const recnave of arrnavitess2) {
 
 
        }
 
        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].index;
      }
      if (!last) {
        last = 1;
      }

      for (let ind = 0; ind < 100; ind++) {
        let myuser = new User();
        myuser._id = new ObjectID();
        myuser.index = last + ind + 1;
        myuser.idapp = idapp;
        myuser.password = '$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG';
        myuser.lang = 'it';
        myuser.email = 'miaemail@email.it';
        myuser.name = 'U' + myuser.index;
        myuser.surname = 'Ar' + myuser.index;
        myuser.verified_email = true;
        myuser.verified_by_aportador = true;
        if (myuser.index < 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' +
          'NAVI CHE SALPANO 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 };
        */
    } else if (mydata.dbop === 'CorreggiTabHours') {

      ris = await Hours.correggiHours(idapp);

    } else if (mydata.dbop === 'setVerifiedByAportadorToALL') {

      ris = await User.setVerifiedByAportadorToALL();

    } else if (mydata.dbop === 'RewriteContribType') {

      ris = populate.rewriteTable('contribtypes');

    } else if (mydata.dbop === 'ReplaceUsername') {

      if (User.isAdmin(req.user.perm)) {
        ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username);
      }

    } else if (mydata.dbop === 'copyFrom1To14') {
      const idapporig = 1;
      const idappdest = 14;
      if (!idapporig || !idappdest)
        return;

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

      //++ Todo: TO FIXIT !
      const mytablesstr = [
        'settings',
        'users',
        'templemail',
        'contribtypes',
        'bots',
        'cfgservers'];

      try {
        let numrectot = 0;
        for (const table of mytablesstr) {
          const mytable = globalTables.getTableByTableName(table);

          tools.mylogshow('copyfromapptoapp: ', table, mytable);

          await mytable.DuplicateAllRecords(idapporig, idappdest).
            then((numrec) => {
              // tools.mylogshow(' REC TO MODIFY: ', rec);
              if (numrec)
                numrectot += numrec;
            });
        }

        ris = true;

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

    } else if (mydata.dbop === 'removeRecordsFav') {
      // Passa le tabelle da users sulle nuove tabelle:
      await User.removerecordsFavorite();

    } else if (mydata.dbop === 'updateReactionsCounts') {
      await Reaction.updateReactionsCounts();

    } else if (mydata.dbop === 'newRecordsFav') {
      // Passa le tabelle da users sulle nuove tabelle:
      await User.moverecordsFavorite(1);
      await User.moverecordsFavorite(2);
      await User.moverecordsFavorite(3);
      await User.moverecordsFavorite(4);
      await User.moverecordsFavorite(5);

    } else if (mydata.dbop === 'emptyTabCatServiziBeni') {

      const { Sector } = require('../models/sector');
      const { SectorGood } = require('../models/sectorgood');
      const { Skill } = require('../models/skill');
      const { Good } = require('../models/good');

      await Sector.deleteMany({});
      await SectorGood.deleteMany({});
      await Skill.deleteMany({});
      ris = await Good.deleteMany({});

    } else if (mydata.dbop === 'emptyDbSkill') {

      // Svuota e Ricrea

      const { Sector } = require('../models/sector');
      const { SectorGood } = require('../models/sectorgood');
      const { Skill } = require('../models/skill');
      const { Good } = require('../models/good');
      const { SubSkill } = require('../models/subskill');
      const { Contribtype } = require('../models/contribtype');
      const { AdType } = require('../models/adtype');
      const { AdTypeGood } = require('../models/adtypegood');
      const { StatusSkill } = require('../models/statusSkill');
      const { CatGrp } = require('../models/catgrp');

      await Sector.deleteMany({});
      await SectorGood.deleteMany({});
      await Skill.deleteMany({});
      await Good.deleteMany({});
      await SubSkill.deleteMany({});
      await Contribtype.deleteMany({});
      await AdType.deleteMany({});
      await AdTypeGood.deleteMany({});
      await StatusSkill.deleteMany({});
      await CatGrp.deleteMany({});

      ris = await populate.popolaTabelleNuove();

    } else if (mydata.dbop === 'ricreaTabCitiesProvinces') {

      // Svuota e Ricrea

      const { City } = require('../models/city');
      const { Province } = require('../models/province');

      await City.deleteMany({});
      await Province.deleteMany({});

      ris = await populate.popolaTabelleNuove();

    } else if (mydata.dbop === 'PopulateTables') {

      ris = populate.popolaTabelleNuove();

    } else if (mydata.dbop === 'RewriteCitiesTable') {

      ris = populate.rewriteTable('cities');
    } else if (mydata.dbop === 'RewriteLevelsTable') {

      ris = populate.rewriteTable('levels');

    } else if (mydata.dbop === 'RewriteProvincesTable') {

      ris = populate.rewriteTable('provinces');

    } else if (mydata.dbop === 'emptyCityProvinces') {

      const { City } = require('../models/city');
      const { Province } = require('../models/province');

      await City.remove({});
      await Province.remove({});

    } else if (mydata.dbop === 'ConvTablesFromIntToString') {

      const { MySkill } = require('../models/myskill');
      const { MyBacheca } = require('../models/mybacheca');
      const { MyHosp } = require('../models/myhosp');
      const { MyGood } = require('../models/mygood');
      const { MyGroup } = require('../models/mygroup');

      console.log('INIZIO - Conversioni');
      // 'myskills',
      // 'mybachecas',
      // 'myhosps',
      // 'mygoods',
      // 'mygroups'

      await ConvertiDaIntAStr(MySkill);
      await ConvertiDaIntAStr(MyBacheca);
      await ConvertiDaIntAStr(MyHosp);
      await ConvertiDaIntAStr(MyGood);
      await ConvertiDaIntAStr(MyGroup);

      console.log('FINE - Conversioni');

    } else if (mydata.dbop === 'Removeinteger') {

      const { MySkill } = require('../models/myskill');
      const { MyBacheca } = require('../models/mybacheca');
      const { MyHosp } = require('../models/myhosp');
      const { MyGood } = require('../models/mygood');
      const { MyGroup } = require('../models/mygroup');

      console.log('INIZIO - Rimozione');

      await RimuoviInteri(MySkill);
      await RimuoviInteri(MyBacheca);
      await RimuoviInteri(MyHosp);
      await RimuoviInteri(MyGood);
      await RimuoviInteri(MyGroup);

      console.log('FINE - Rimozione');


    } else if (mydata.dbop === 'createAllCircuits') {
      const { Province } = require('../models/province');

      const arrProv = await Province.find({});
      for (const recprov of arrProv) {
        await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
      }

    } else if (mydata.dbop === 'ImpostaMinMaxPersonali') {

      await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, '');

    } else if (mydata.dbop === 'ImpostaMinMaxPersonaliCircuito') {

      await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);

    } else if (mydata.dbop === 'ImpostaMinMaxComunitari') {

      await Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax);

    } else if (mydata.dbop === 'ImpostaMinMaxCollettivi') {

      await Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax);

    } else if (mydata.dbop === 'ImpostaDefMinMaxPersonali') {

      await Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);

    } else if (mydata.dbop === 'ImpostaDefMinMaxCollettivi') {

      await Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);

    } else if (mydata.dbop === 'AbilitaTuttiCircuiti') {

      await Circuit.AbilitaTuttiCircuiti(idapp);

    } else if (mydata.dbop === 'AzzeraRegolamentiTuttiCircuiti') {

      await Circuit.AzzeraRegolamentiTuttiCircuiti(idapp);

    } else if (mydata.dbop === 'setstrProvByIdCityCircuits') {

      await Circuit.setstrProvByIdCityCircuits(idapp);

    } else if (mydata.dbop === 'updateSaldoAndTransato_AllAccounts') {

      await Account.updateSaldoAndTransato_AllAccounts(idapp);

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

    return ris;

  } catch (e) {
    console.log(e.message);
  }
};

async function ConvertiDaIntAStr(mytable) {
  try {
    console.log('INIZIO - ConvertiDaIntAStr ', mytable.modelName);

    return await mytable.find({ '_id': { $type: 16 } })
      .then(async (arr) => {
        console.log('num record ', arr.length)

        let ind = 0;
        for (let x of arr) {

          const idnew = x._id;

          if (idnew < 10000) {

            const idint = parseInt(x._id, 10) + 10000;

            const myrec = new mytable(x._doc);

            myrec._doc.date_created = x._doc.date_created;
            myrec._doc.date_updated = x._doc.date_updated;

            if (!myrec._doc.date_updated) {
              if (myrec.hasOwnProperty('date_created'))
                myrec._doc.date_updated = myrec._doc.date_created;
            }
            if ((myrec.hasOwnProperty('date_updated') && !myrec._doc.date_created))
              myrec._doc.date_created = myrec._doc.date_updated;
            myrec._doc._id = idint + '';

            let ris = await myrec.save((async function (err, doc) {
              if (doc) {
                ind++;
                //await mytable.findOneAndRemove({ _id: parseInt(doc._id, 10) });
                console.log('++Add (', ind, ')', doc._id);
              } else {
                const myid = parseInt(err.keyValue._id, 10) + 0;
                const canc = await mytable.findOneAndRemove({ _id: myid });
                if (canc)
                  console.log('err', err.message, 'canc', canc._doc._id);
              }

            }));
          }

        }
        console.log('FINE - ConvertiDaIntAStr ', mytable.modelName);
      });



  } catch (err) {
    console.error(err);
  }
}
async function RimuoviInteri(mytable) {
  try {
    console.log('INIZIO - RimuoviInteri ', mytable.modelName);

    const arr = await mytable.find({ '_id': { $lte: 10000 } })
    console.log('   search interi...', arr.length);

    const ris = await mytable.deleteMany({ '_id': { $lte: 10000 } })

    console.log('FINE - RimuoviInteri ', mytable.modelName, ris);

  } catch (err) {
    console.error(err);
  }
}

async function eseguiDbOpUser(idapp, mydata, locale, req, res) {

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

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

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

  let mystr = '';

  try {

    if (mydata.dbop === 'CreateAccountCircuits') {

      const allcirc = await Circuit.find({ idapp });

      for (const mycirc of allcirc) {
        // Il Conto Comunitario prende il nome del circuito !
        await Account.createAccount(idapp, '', mycirc.name, true, '', mycirc.path);

      }

    } else if (mydata.dbop === 'saveStepTut') {
      await User.findOneAndUpdate({ _id: mydata._id },
        { $set: { 'profile.stepTutorial': mydata.value } });
    } else if (mydata.dbop === 'noNameSurname') {
      await User.findOneAndUpdate({ _id: mydata._id },
        { $set: { 'profile.noNameSurname': mydata.value } });
    } else if (mydata.dbop === 'noCircuit') {
      await User.findOneAndUpdate({ _id: mydata._id },
        { $set: { 'profile.noCircuit': mydata.value } });
    } else if (mydata.dbop === 'noCircIta') {
      await User.findOneAndUpdate({ _id: mydata._id },
        { $set: { 'profile.noCircIta': mydata.value } });
    } else if (mydata.dbop === 'noFoto') {
      await User.findOneAndUpdate({ _id: mydata._id },
        { $set: { 'profile.noFoto': mydata.value } });
    }

  } catch (e) {

  }

};

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

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

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

  try {
    let ris = await eseguiDbOp(idapp, mydata, locale, req, res);

    if (!ris) {
      ris = {};
    }

    ris = await User.updateMyData(ris, idapp, req.user.username);

    res.send({ code: server_constants.RIS_CODE_OK, data: ris.data });

  } catch (e) {
    res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });

    console.log(e.message);
  }

});

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

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

  try {
    let ris = await eseguiDbOpUser(idapp, mydata, locale, req, res);

    if (!ris) {
      ris = {};
    }

    ris = await User.updateMyData(ris, idapp, req.user.username);

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

  } catch (e) {
    res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });

    console.log(e.message);
  }

});

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

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

  try {
    const { nummsgsent, numrec, textsent, text } = await telegrambot.sendMsgFromSiteToBotTelegram(idapp, req.user, mydata);

    return res.send({ numrec, nummsgsent, textsent, text });

  } catch (e) {
    res.status(400).send();
    res.send({ code: server_constants.RIS_CODE_ERR, msg: e });

    console.log(e.message);
  }

});


module.exports = router;
