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

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

mongoose.set('debug', false);

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

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

const _ = require('lodash');

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

const SiteSchema = new Schema({
  active: {
    type: Boolean,
  },
  idapp: {
    type: String,
  },
  name: {
    type: String,
  },
  adminemail: {
    type: String,
  },
  manageremail: {
    type: String,
  },
  replyTo: {
    type: String,
  },
  host: {
    type: String,
  },
  host_ip: {
    type: String,
  },
  host_test: {
    type: String,
  },
  host_test_ip: {
    type: String,
  },
  host_api: {
    type: String,
  },
  host_api_ip: {
    type: String,
  },
  host_testapi: {
    type: String,
  },
  host_testapi_ip: {
    type: String,
  },
  cf_token: {
    type: String,
  },
  cf_zoneId: {
    type: String,
  },
  servermail: {
    type: String,
  },
  servermailip: {
    type: String,
  },
  dkim: {
    type: String,
  },
  enable_servermail: {
    type: Boolean,
  },
  portapp: {
    type: String,
  },
  dir: {
    type: String,
  },
  dir_test: {
    type: String,
  },
  email_from: {
    type: String,
  },
  email_pwd: {
    type: String,
  },
  telegram_key: {
    type: String,
  },
  telegram_bot_name: {
    type: String,
  },
  telegram_key_test: {
    type: String,
  },
  load_process_telegram: {
    type: Boolean,
  },
  load_process_telegram_test: {
    type: String,
  },
  teleg_cfg: {
    type: String,
  },
  teleg_cfg_test: {
    type: String,
  },
  telegram_bot_name_test: {
    type: String,
  },
  telegram_support_chat: {
    type: String,
  },
  telegram_gruppi_territoriali_senzainvito: {
    type: String,
  },
  pathreg_add: {
    type: String,
  },
  who: {
    type: String
  },
  status: {
    type: String
  },
  note: {
    type: String
  },
  domain_provider: {
    type: String,
  },
  domain_expiring: {
    type: Date
  },
  next_payment: {
    type: Date
  },
  description: {
    type: String,
  },
  keywords: {
    type: String,
  },
  confpages: {
    font: { type: String, default: '' },
    col_toolbar: { type: String, default: '' },
    col_bgfooter: { type: String, default: '' },
    show_darkopt: { type: Boolean, default: false },
    showButtHome: { type: Boolean, default: false },
    showProfile: { type: Boolean, default: false },
    showUserMenu: { type: Boolean, default: true },
    showiscrittiMenu: { type: Boolean, default: false },
    showRegButton: { type: Boolean, default: false },
    enableReg: { type: Boolean, default: false },
    showNL: { type: Boolean, default: false },
    sendNewsletter: { type: Boolean, default: false },
    showMsgs: { type: Boolean, default: false },
    showNotif: { type: Boolean, default: false },
    showCoins: { type: Boolean, default: false },
    showRIS: { type: Boolean, default: false },
    showMenuCoins: { type: Boolean, default: false },
    showNameSurname: { type: Boolean, default: false },
    showCompetenze: { type: Boolean, default: false },
    showConnected: { type: Boolean, default: false },
    bookingEvents: { type: Boolean, default: false },
    enableEcommerce: { type: Boolean, default: false },
    enableAI: { type: Boolean, default: false },
    enablePoster: { type: Boolean, default: false },
    enableTrasporti: { type: Boolean, default: false },
    enableGroups: { type: Boolean, default: false },
    enableCircuits: { type: Boolean, default: false },
    enableGoods: { type: Boolean, default: false },
    enableServices: { type: Boolean, default: false },
    enableActivities: { type: Boolean, default: false },
    enableHosps: { type: Boolean, default: false },
    enableEvents: { type: Boolean, default: false },
    enableProj: { type: Boolean, default: false },
    enableTodos: { type: Boolean, default: false },
    enableRegByBot: { type: Boolean, default: false },
    enableRegMultiChoice: { type: Boolean, default: false },
    enableTokenExpired: { type: Boolean, default: false },
    enableDebugOn: { type: Boolean, default: false },
    enabledRegNeedTelegram: { type: Boolean, default: false },
    showViewEventi: { type: Boolean, default: false },
    showViewGroups: { type: Boolean, default: false },
    showViewCircuits: { type: Boolean, default: false },
    showViewUsers: { type: Boolean, default: false },
    showViewBooking: { type: Boolean, default: false },
    showViewProfile: { type: Boolean, default: false },
    showViewCart: { type: Boolean, default: false },
    showViewOrders: { type: Boolean, default: false },
    enablePwa: { type: Boolean, default: false },
    lang: {
      type: Number,
      default: 0,
    },
    videoPromo: { type: String, default: '' },
    PDFPromo: { type: String, default: '' },
  },
  confsite: {
    options: {  // ConfSite
      type: Number,
      default: 0,
    },
  },
  policy: {
    show: { type: Boolean, default: false },
    owneremail: { type: String },
    siteName: { type: String },
    ownerDataName: { type: String },
    managerData: { type: String },
    includeData: { type: String },
    url: { type: String },
    lastdataupdate: { type: String },
    country: { type: String },
  },
  contacts: {
    facebook: { type: String, default: '' },
    instagram: { type: String, default: '' },
    whatsapp: { type: String, default: '' },
    whatsapp_home: { type: Boolean, default: false },
    telegram: { type: String, default: '' },
    youtube: { type: String, default: '' },
    email: { type: String, default: '' },
    address: { type: String, default: '' },
    map: { type: String, default: '' },
    info2: { type: String, default: '' },
    cell: { type: String, default: '' },
  },
  ecomm: {
    enablePreOrders: { type: Boolean, default: false },
    NoteExtraOnCart: { type: String, default: '' },
  },
  idMyGroup: {
    type: String,
  },
});

var Site = module.exports = mongoose.model('Site', SiteSchema);

module.exports.getFieldsForSearch = function () {
  return []
};

module.exports.executeQueryTable = async function (idapp, params, userreq) {
  params.fieldsearch = this.getFieldsForSearch();
  // return tools.executeQueryTable(this, null, params);

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

  // Solo l'Admin puó leggerlo

  const extrapar = params.extrapar;

  if (extrapar) {
    if (User.isManager(userreq.perm)) {
      return await Site.findOne({ idapp: extrapar }).lean();
    } else {
      return await Site.findOne({ idapp: extrapar }, {
        name: 1, manageremail: 1,
        confsite: 1,
        description: 1,
        keywords: 1,
      }).lean();
    }
  }

  if (User.isAdmin(userreq.perm)) {
    const myarr = await Site.find({});

    if (myarr.length === 0) {
      /*  {
          "_id" : new ObjectId("620a71e194438ecd1acfdbca"),
          "idapp" : "14",
          "chiave" : "vers",
          "userId" : "ALL",
          "valore" : "0.3.21"
      }*/

    }

    // return await Site.find({}).lean();
    return ({ count: myarr.length, rows: myarr })

  }

};

module.exports.findAll = async function () {

  const myfind = { active: true };

  return await Site.find(myfind).lean();

};

module.exports.findAllIdApp = async function (idapp) {

  let myfind = { idapp, active: true };

  let rec = await Site.findOne(myfind).lean();
  if (rec) {

    rec.email_pwd = '';
    rec.telegram_key = '';
    rec.telegram_key_test = '';
    rec.cf_token = '';
    rec.cf_zoneId = '';
    // rec.confsite = {};

    return rec;
  } else {
    myfind = { name: 'local' };
    let rec = await Site.findOne(myfind).lean();
    if (!rec) {
      const mysite = new Site();
      mysite.name = 'local';

      await mysite.save();

      mysite.idapp = idapp;
      return mysite;
    } else {
      return rec;
    }
  }
  return {};

};

module.exports.generateNewSite_IdApp = async function (idapp, params, createpage) {

  const { MyPage } = require('../models/mypage');

  let ris = null;

  try {

    if (idapp) {
      ris = await Site.find({ idapp: idapp.toString(), host: params.host });
    } else {

      for (let idapp = 20; idapp <= 100; idapp++) {
        ris = await Site.find({ idapp: idapp.toString(), host: params.host });
        break;
      }
    }

    if (ris && ris.length === 0) {
      const paramSite = _.pick(params, ['name', 'host', 'email']);
      let mysite = new Site(paramSite);

      mysite.active = true;
      mysite.idapp = idapp.toString();
      mysite.adminemail = params.email;

      const ris = await mysite.save();

      if (createpage) {
        // 1. Crea Pagina principale HOME - Loggato
        let myp = new MyPage({
          order: 10,
          idapp: mysite.idapp,
          path: 'home',
          active: true,
          title: 'Home',
        });
        let rispag = await myp.save();

        // 2. Crea Pagina principale HOME - Non Loggato
        myp = new MyPage({
          order: 10,
          idapp: mysite.idapp,
          path: 'presentazione',
          active: true,
          title: 'Presentazione',
        });
        rispag = await myp.save();
      }

      if (ris)
        return mysite.idapp;
      else
        return '';
    }

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

  return '';

};

module.exports.createFirstUserAdmin = async function () {

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

  try {

    let arrSite = await Site.find({ idapp: { $exists: true } }).lean();

    for (const mysite of arrSite) {
      if (mysite.idapp > 0) {
        const numusers = await User.countDocuments({ idapp: mysite.idapp });
        if (numusers === 0) {
          // Non esistono utenti, quindi creo quello di Admin
          console.error('❌❌❌❌ ***** Non esistono utenti, quindi creo quello di Admin ! app=', mysite.idapp);

          const utenteadmin = { idapp: '13', username: shared_consts.ADMIN_USER_SERVER };

          const newuser = new User(utenteadmin);
          newuser._id = new ObjectId();
          newuser.idapp = mysite.idapp;
          newuser.profile.mygroups = [];
          newuser.profile.mycircuits = [];

          await newuser.save();
        }
      }

    }

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

};

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

