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

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

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


module.exports = {

  async insertIntoDb(tablename, table) {

    try {
      const pathfile = Path.join(__dirname, tablename + '.js');
      if (tools.isFileExists(pathfile)) {
        const mydbfile = require(pathfile);

        if (mydbfile && mydbfile.list) {
          return table.insertMany(mydbfile.list, {ordered: false}).
              then((ris) => {
                console.log('Populate table ', tablename);
                return !!ris;
              });
        }
      }
    } catch (e) {
      console.log('error insertIntoDb', e);
    }

  },

  async insertIntoDb_NoDuplicate(attiva, tablename, table, field) {

    let numrec = 0;
    try {

      if (!attiva && await table.countDocuments({}) > 0)
        return;

      const pathfile = Path.join(__dirname, tablename + '.js');
      if (tools.isFileExists(pathfile)) {

        const mydbfile = require(pathfile);

        if (mydbfile && mydbfile.list) {
          for (const rec of mydbfile.list) {
            let obj = {};
            obj[field] = rec[field];

            var mynewrec = new table(rec);

            if (rec.hasOwnProperty('idapp')) {
              obj.idapop = rec['idapp'];
            }

            const exist = await table.find(obj);
            if (exist.length <= 0) {
              try {
                const ris = await mynewrec.save();
                if (ris) {
                  numrec++;
                }
              } catch (e) {
                console.log('error ', e);
              }

            }
          }

          if (numrec > 0)
            console.log('*** Insert', numrec, 'record on ' + tablename);

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

  },

  async rewriteTable(table) {

    let mytab = null;
    let field = '';

    try {
      const {City} = require('../models/city');
      const {Province} = require('../models/province');
      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 {Level} = require('../models/level');

      if (table === 'cities') {
        mytab = City;
        field = 'comune';
      } else if (table === 'provinces') {
        mytab = Province;
        field = 'descr';
      } else if (table === 'sectors') {
        mytab = Sector;
        field = 'descr';
      } else if (table === 'sectorgoods') {
        mytab = SectorGood;
        field = 'descr';
      } else if (table === 'skills') {
        mytab = Skill;
        field = 'descr';
      } else if (table === 'goods') {
        mytab = Good;
        field = 'descr';
        //} else if (table === 'subskills') {
        //  mytab = SubSkill;
        // field = 'descr';
      } else if (table === 'contribtypes') {
        mytab = Contribtype;
        field = 'label';
      } else if (table === 'levels') {
        mytab = Level;
        field = 'descr';
      }

      if (mytab) {
        await mytab.collection.drop();
        // mongoose.connection.db.dropCollection(table, function(err) {
          console.log('Delete ', table);
          // await mytab.remove({});

          this.insertIntoDb_NoDuplicate(false, table, mytab, field);
//        });
      }
      return true;
    } catch (e) {
      console.error('Err: ' + e);
    }
    return false;
  },

  async popolaTabelleNuove() {
    const abilita = true;
    const scrivi_citta = false;
    const scrivi_contribtype = false;

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

    let ris = null;
    try {

      console.log('INIZIO - popolaTabelleNuove');

      for (const rec of shared_consts.TABLES_POPULATE_DATA) {
        let mytable = globalTables.getTableByTableName(rec.table);

        let attiva = abilita;
        if (rec.table === 'cities' || rec.table === 'province') {
          attiva = scrivi_citta;
        }
        if (rec.table === 'contribtypes') {
          attiva = scrivi_contribtype;
        }

        await this.insertIntoDb_NoDuplicate(attiva, rec.table, mytable, rec.key);
      }

      console.log('FINE - popolaTabelleNuove');

      return true;
    } catch (e) {
      console.error('Err: ' + e);
      return false;
    }

  },

};

