const os = require('os');

const fs = require('fs');

const path = require('path');

require('../config/config');

require('../models/subscribers');

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

const {User} = require('../models/user');
const {MyGroup} = require('../models/mygroup');
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 {Skill} = require('../models/skill');
const {Good} = require('../models/good');
const {SubSkill} = require('../models/subskill');
const {MySkill} = require('../models/myskill');
const {MyGood} = require('../models/mygood');
const {MyBacheca} = require('../models/mybacheca');
const {MyHosp} = require('../models/myhosp');
const {StatusSkill} = require('../models/statusSkill');
const {City} = require('../models/city');
const {Province} = require('../models/province');
const {Sector} = require('../models/sector');
const {SectorGood} = require('../models/sectorgood');
const {CatGrp} = require('../models/catgrp');
const {Level} = require('../models/level');
const {AdType} = require('../models/adtype');
const {AdTypeGood} = require('../models/adtypegood');
const {Circuit} = require('../models/circuit');
const {Account} = require('../models/account');
const {Movement} = require('../models/movement');
const Pickup = require('../models/pickup');
const {Newstosent} = require('../models/newstosent');
const {MyPage} = require('../models/mypage');
const {MyBot} = require('../models/bot');
const {CfgServer} = require('../models/cfgserver');
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 {MsgTemplate} = require('../models/msg_template');
const {Graduatoria} = require('../models/graduatoria');
const Product = require('../models/product');
const Producer = require('../models/producer');
const Cart = require('../models/cart');
const OrdersCart = require('../models/orderscart');
const Storehouse = require('../models/storehouse');
const Department = require('../models/department');
const ShareWithUs = require('../models/sharewithus');
const Site = require('../models/site');
const IscrittiConacreis = require('../models/iscrittiConacreis');
const Group = require('../models/group');
const {Todo} = require('../models/todo');
const Hours = require('../models/hours');
const Order = require('../models/order');
const Cash = require('../models/cash');
const CashCategory = require('../models/cashCategory');
const CashSubCategory = require('../models/cashSubCategory');

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

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

module.exports = {

  getTableByTableName(tablename) {

    let mytable = '';
    if (tablename === 'users')
      mytable = User;
    else if (tablename === shared_consts.TAB_MYGROUPS)
      mytable = MyGroup;
    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 === 'products')
      mytable = Product;
    else if (tablename === 'storehouses')
      mytable = Storehouse;
    else if (tablename === 'departments')
      mytable = Department;
    else if (tablename === 'sharewithus')
      mytable = ShareWithUs;
    else if (tablename === 'sites')
      mytable = Site;
    else if (tablename === 'iscritticonacreis')
      mytable = IscrittiConacreis;
    else if (tablename === 'groups')
      mytable = Group;
    else if (tablename === 'todos')
      mytable = Todo;
    else if (tablename === 'hours')
      mytable = Hours;
    else if (tablename === 'orders')
      mytable = Order;
    else if (tablename === 'cashs')
      mytable = Cash;
    else if (tablename === 'cashCategorys')
      mytable = CashCategory;
    else if (tablename === 'cashSubCategorys')
      mytable = CashSubCategory;
    else if (tablename === 'producers')
      mytable = Producer;
    else if (tablename === 'carts')
      mytable = Cart;
    else if (tablename === 'orderscart')
      mytable = OrdersCart;
    else if (tablename === 'sendmsgs')
      mytable = SendMsg;
    else if (tablename === 'wheres')
      mytable = Where;
    else if (tablename === 'myevents')
      mytable = MyEvent;
    else if (tablename === 'contribtypes')
      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 === 'bots')
      mytable = MyBot;
    else if (tablename === 'cfgservers')
      mytable = CfgServer;
    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 === 'msg_templates')
      mytable = MsgTemplate;
    else if (tablename === 'navepersistente')
      mytable = NavePersistente;
        // else if (tablename === 'listaingressos')
    //   mytable = ListaIngresso;
    else if (tablename === 'graduatorias')
      mytable = Graduatoria;
    else if (tablename === 'skills')
      mytable = Skill;
    else if (tablename === 'goods')
      mytable = Good;
    else if (tablename === 'subskills')
      mytable = SubSkill;
    else if (tablename === shared_consts.TABLES_MYSKILLS)
      mytable = MySkill;
    else if (tablename === shared_consts.TABLES_MYBACHECAS)
      mytable = MyBacheca;
    else if (tablename === shared_consts.TABLES_MYHOSPS)
      mytable = MyHosp;
    else if (tablename === shared_consts.TABLES_MYGOODS)
      mytable = MyGood;
    else if (tablename === 'statusSkills')
      mytable = StatusSkill;
    else if (tablename === 'cities')
      mytable = City;
    else if (tablename === 'provinces')
      mytable = Province;
    else if (tablename === 'sectors')
      mytable = Sector;
    else if (tablename === 'sectorgoods')
      mytable = SectorGood;
    else if (tablename === 'catgrps')
      mytable = CatGrp;
    else if (tablename === 'levels')
      mytable = Level;
    else if (tablename === 'adtypes')
      mytable = AdType;
    else if (tablename === 'adtypegoods')
      mytable = AdTypeGood;
    else if (tablename === 'circuits')
      mytable = Circuit;
    else if (tablename === 'accounts')
      mytable = Account;
    else if (tablename === 'movements')
      mytable = Movement;
    else if (shared_consts.TablePickup.includes(tablename))
      mytable = Pickup;
    //else if (shared_consts.TableCities.includes(tablename))
    // mytable = City;

    return mytable;
  },

  SendMsgToParam: async function(idapp, params) {

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

      let query = {idapp};
      let addquery = {};

      let invia = true;

      if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) {
        addquery = {};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_SOCI) {
        addquery = {'profile.socio': true};
      } else if (params.typemsg ===
          shared_consts.TypeMsg.SEND_TO_SOCIO_RESIDENTE) {
        addquery = {'profile.socioresidente': true};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_CONSIGLIO) {
        addquery = {'profile.consiglio': true};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_NON_SOCI) {
        addquery = {'profile.socio': false};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_PAOLO) {
        addquery = {username: 'paoloar77'};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_USER) {
        addquery = {username: params.usernameDest};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) {
        addquery = {username: params.usernameDest};
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_USERNAME_TELEG) {
        addquery = {
          'profile.teleg_id': {$gt: 1},
          $or: [
            {'profile.username_telegram': {$exists: false}},
            {'profile.username_telegram': {$exists: true, $eq: ''}}],
        };
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_TELEG_NO_VERIF_BY_APORTADOR) {
        addquery = {
          'profile.teleg_id': {$gt: 1},
          'profile.username_telegram': {$exists: true},
          $expr: { $gt: [ { $strLenCP: "$profile.username_telegram" }, 3 ] },
            'verified_by_aportador': {$exists: false}
        };
      } else if (params.typemsg === shared_consts.TypeMsg.SEND_TO_GROUP) {
        if (params.groupnameDest) {
          addquery = {
            'profile.mygroups': {
              $elemMatch: {groupname: {$eq: params.groupnameDest}},
            },
          };
        } else {
          invia = false;
        }
      }

      let numrec = 0;
      let nummsgsent = 0;

      if (invia) {

        const allquery = {...query, ...addquery};

        const arrusers = await User.find(
            allquery,
            {
              username: 1,
              'profile.teleg_id': 1,
            },
        ).lean();

        for (const user of arrusers) {

          const mytitle = tools.convertSpecialTags(user, params.title);
          const mycontent = tools.convertSpecialTags(user, params.content);

          let risult = null;

          if (params.sendreally) {
            if (tools.isBitActive(params.typesend,
                shared_consts.TypeSend.PUSH_NOTIFICATION)) {
              risult = tools.sendNotificationToUser(user._id, mytitle, mycontent, params.openUrl, params.openUrl2, params.tag,
                  params.actions).
                  then(ris => {

                  }).
                  catch(e => {
                    console.error(e.message);
                  });

            } else if (tools.isBitActive(params.typesend, shared_consts.TypeSend.TELEGRAM)) {
              const telegid = user.profile.teleg_id;

              if (telegid > 0) {
                risult = await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, mycontent);
                await tools.snooze(100);
              }
            }
          }

          numrec++;
          if (params.sendreally && risult) {
            nummsgsent++;
          }

          if (nummsgsent > 0 && (nummsgsent % 100) === 0) {
            console.log('Inviati ', nummsgsent, 'messaggi...');
          }
        }
      }

      if (nummsgsent > 0) {
        console.log('FINE Invio Messaggi ! Inviati Totali: ', nummsgsent, 'su', numrec);
      }

      return {
        numrec,
        nummsgsent,
      };
    } catch (e) {
      console.error('SendMsgToParam', e);
    }

  },

  SendMsgToAll: async function(idapp, params) {

    params.typemsg = shared_consts.TypeMsg.SEND_TO_ALL;
    params.sendreally = true;
    params.typesend = shared_consts.TypeSend.PUSH_NOTIFICATION;

    return this.SendMsgToParam(idapp, params);
  },

};
