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

mongoose.Promise = global.Promise;
mongoose.level = 'F';

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

const { User } = require('../models/user');
const { Movement } = require('../models/movement');
const { Circuit } = require('../models/circuit');
const { MyGroup } = require('../models/mygroup');
const { Settings } = require('../models/settings');

const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');


// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
  schema.options.usePushEach = true;
});

const StatSchema = new Schema({
  ...{
    _id: {
      type: String,
    },
    idapp: {
      type: String,
      required: true,
    },
    num_reg: {
      type: Number,
    },
    date_created: {
      type: Date,
      default: Date.now,
    },
    num_reg: Number,
    num_reg_today: Number,
    online_today: Number,
    activeusers: Number,
    num_teleg_attivo: Number,
    num_autorizzati: Number,
    num_autorizzare: Number,
    num_teleg_pending: Number,
    arr_nations: [],
    numreg_untilday: Number,
    reg_daily: [],
    reg_weekly: [],
    lastsreg: [],
    lastsonline: [],
    lastssharedlink: [],
    diffusorilist: [],
    receiveRislist: [],
    receiveRislistgroup: [],
    listlinksreg: [],
    strettelist: [],
    num_transaz_tot: Number,
    tot_RIS_transati: Number,
    num_circuiti: Number,
    num_circuiti_attivi: Number,
    num_annunci: Number,
    last_transactions: [],
  },
});

StatSchema.statics.updateStats = async function (idapp, datastat) {

  datastat.last_transactions = await Movement.getLastN_Transactions(idapp, 5, 5);

  return datastat;
};

StatSchema.statics.calculateStats = async function (idapp) {
  const Stat = this;

  try {

    let datastat = {
      idapp,
      num_reg: await User.getUsersRegistered(idapp),
      num_reg_today: await User.getUsersRegisteredToday(idapp),
      online_today: await User.getUsersOnLineToday(idapp),
      activeusers: await User.getUsersOnLineActive(idapp),
      num_teleg_attivo: await User.getUsersTelegramAttivo(idapp),
      num_autorizzati: await User.getUsersAutorizzati(idapp),
      num_autorizzare: await User.getUsersAutorizzare(idapp),
      num_teleg_pending: await User.getUsersTelegramPending(idapp),
      arr_nations: await User.findAllDistinctNationality(idapp),
      numreg_untilday: await User.calcnumRegUntilDay(idapp),
      reg_daily: await User.calcRegDaily(idapp),
      reg_weekly: await User.calcRegWeekly(idapp),
      lastsreg: await User.getLastUsers(idapp),
      lastsonline: await User.getLastOnlineUsers(idapp),
      lastssharedlink: await User.getLastSharedLink(idapp),
      diffusorilist: await User.getDiffusoriUsers(idapp),
      listlinksreg: await User.getListLinkReg(idapp),
      receiveRislist: await User.getReceiveRISUsers(idapp),
      receiveRislistgroup: await MyGroup.getReceiveRISGroups(idapp),
      strettelist: await User.getLastStretteDiManoUsers(idapp),
      num_transaz_tot: await Movement.getTotal_Transactions(idapp),
      tot_RIS_transati: await Movement.getTot_RIS_Transati(idapp),
      num_circuiti: await Circuit.getnumCircuits(idapp),
      num_circuiti_attivi: await Circuit.getnumActiveCircuits(idapp),
      num_annunci: await User.getnumAnnunci(idapp),
    };

    // Trova il record di oggi:
    const trova_se_oggi = await Stat.findOne({ idapp, date_created: { $gte: new Date(new Date().setHours(0, 0, 0, 0)) } }).lean();

    if (trova_se_oggi) {
      // Aggiorna il record di oggi:
      const ris = await Stat.findOneAndUpdate(
        { _id: trova_se_oggi._id },
        { $set: datastat },
        { returnDocument: "after" });
      // console.log('ris', ris);
    } else {
      // Aggiungi un nuovo record:
      await Stat.insertMany([datastat]);
    }

    return datastat;

  } catch (e) {
    console.error('Error', e);
    return null;
  }

};

StatSchema.statics.getStats = async function (idapp) {
  const Stat = this;

  const minuti = await Settings.getValDbSettings(idapp, 'NUMMINUTI_STAT', 30);

  // Ottieni l'ultimo record salvato:
  const rec = await Stat.findOne({ idapp })
    .sort({ date_created: -1 })
    .lean();

  let isOld = true;

  if (rec) {
    // se rec.date_created è più vecchio di minuti fa, allora ricalcola.
    const dateCreated = new Date(rec.date_created);
    const now = new Date();

    // Calcola la differenza in millisecondi
    const difference = now - dateCreated; // Differenza in millisecondi

    // Controlla se la differenza è maggiore di 10 minuti (10 * 60 * 1000 ms)
    isOld = (difference > minuti * 60 * 1000);
  }

  let datastat = null;

  if (tools.testing()) {
    isOld = true;
  }

  if (isOld) {
    datastat = await Stat.calculateStats(idapp);

  } else {
    datastat = rec;
  }

  datastat = await Stat.updateStats(idapp, datastat);

  return datastat;

};


const Stat = mongoose.model('Stat', StatSchema);

Stat.createIndexes()
  .then(() => { })
  .catch((err) => { throw err; });


module.exports = { Stat };
