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

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);
              }

              //await table.insertMany(rec, {ordered: false});
            }
          }

          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 = '';

    const {City} = require('../models/city');
    const {Province} = require('../models/province');
    const {Sector} = require('../models/sector');
    const {Skill} = require('../models/skill');
    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 === 'skills') {
      mytab = Skill;
      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) {
      console.log('Delete ', table)
      await mytab.deleteMany({});

      await this.insertIntoDb_NoDuplicate(false, table, mytab, field)
    }

    return true;

  },

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

    let ris = null;
    try {

      const {City} = require('../models/city');
      const {Province} = require('../models/province');

      console.log('INIZIO - popolaTabelleNuove')

      // Sectors
      const {Sector} = require('../models/sector');
      await this.insertIntoDb_NoDuplicate(abilita, 'sectors', Sector, 'descr')

      // CatGrps
      const {CatGrp} = require('../models/catgrp');
      await this.insertIntoDb_NoDuplicate(abilita, 'catgrps', CatGrp, 'descr')

      // Skills (Competenze)
      const {Skill} = require('../models/skill');
      await this.insertIntoDb_NoDuplicate(abilita, 'skills', Skill, 'descr')

      // SubSectors
      const {SubSkill} = require('../models/subskill');
      await this.insertIntoDb_NoDuplicate(abilita, 'subskills', SubSkill, 'descr')

      // Levels
      const {Level} = require('../models/level');
      await this.insertIntoDb_NoDuplicate(abilita, 'levels', Level, 'descr')

      // Status
      const {StatusSkill} = require('../models/statusSkill');
      await this.insertIntoDb_NoDuplicate(abilita, 'statusskills', StatusSkill, 'descr')

      // Cities
      await this.insertIntoDb_NoDuplicate(scrivi_citta, 'cities', City, 'comune')

      // Province
      await this.insertIntoDb_NoDuplicate(scrivi_citta, 'provinces', Province, 'descr')
      console.log('FINE - Scrivo le Città')

      // Contribtypes
      const {Contribtype} = require('../models/contribtype');
      await this.insertIntoDb_NoDuplicate(false, 'contribtypes', Contribtype, 'label')

      // AdTypes
      const {AdType} = require('../models/adtype');
      await this.insertIntoDb_NoDuplicate(abilita, 'adtypes', AdType, 'descr')

      console.log('FINE - popolaTabelleNuove')

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

  },

};

