const mongoose = require('mongoose').set('debug', false)
const Subscription = require('../../models/subscribers');

//const { ListaIngresso } = require('../../models/listaingresso');
const { Graduatoria } = require('../../models/graduatoria');
const { User } = require('../../models/user');

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

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


module.exports = {
  doOtherThingsAfterDeleted: async function (tablename, rec, notifBot, req) {
    try {

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

      let ris = null;

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

      if (tablename === 'users') {

        // await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username);

        // Controlla se aveva invitati, li regala a quello sopra
        const arrap = await User.getDownlineByUsername(rec.idapp, rec.username);
        for (let user of arrap) {

          await User.findOneAndUpdate({
            idapp: rec.idapp,
            username: user.username
          }, { $set: { aportador_solidario: rec.aportador_solidario } }, { new: false });

          let msg = 'Spostato ' + user.name + ' ' + user.surname + ' sotto di ' + rec.aportador_solidario;
          telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg);
        }

        // Delete also all the subscribers record of this User
        ris = Subscription.deleteOne({ userId: rec._id })
      }

      if (!!ris) {

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

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

      }

      return ris

    } catch (e) {
      console.error(e.message);
      return false
    }

  },
  doOtherThingsAfterDuplicated: async function (tablename, myrec, mynewrec) {
    try {
      if (tablename === 'users') {
        // Delete also all the subscribers record of this User

      }
      return { myrec }

    } catch (e) {
      return false
    }
    return true;
  }
};
