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

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

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


module.exports = {

  async insertIntoDb(tablename, table) {

    try {
      const pathfile = Path.join(__dirname, tablename + '.js');
      if (await tools.isFileExistsAsync(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, field2) {
    let numrec = 0;
    let numupdated = 0;
    try {
      if (!attiva && await table.countDocuments({}) > 0) return;

      let primavolta = false;

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

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

            if (rec.hasOwnProperty('_id')) {
              query._id = rec._id;
            }

            if (rec.hasOwnProperty('idapp')) {
              query.idapp = rec.idapp;
            }

            try {

              const existingDoc = await table.findOne(query);
              if (!existingDoc) {
                if (!primavolta) {
                  console.log('Tabella: ', tablename);
                  primavolta = true;
                }

                console.log('ADDING: ', query);

                const newDoc = new table(rec);
                const insertedDoc = await newDoc.save();
                if (insertedDoc) {
                  console.log('Inserted document with _id:', insertedDoc._id);

                } else {
                  console.log('   ... Non inserito !');
                }

                
              } else {
                // Il documento esiste, lo aggiorniamo
                const ris = await table.updateOne({ _id: existingDoc._id }, { $set: rec });
                if (ris && ris.modifiedCount > 0)
                  numupdated++;
              }
            } catch (e) {
              console.log('Error processing record: ', tablename, e);
            }
          }

          if (numrec > 0 || numupdated > 0) {
            console.log(`------- *** Inseriti ${numrec} e aggiornati ${numupdated} record in ${tablename} ------ `);
          }
        }
      }
    } catch (e) {
      console.log('Error in insertIntoDb_NoDuplicate:', 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);

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

        if (mytable) {
          await this.insertIntoDb_NoDuplicate(attiva, rec.table, mytable, rec.key, rec.key2);
        } else {
          console.error('Tabella ', mytable, ' non esistente!')
        }
      }

      // FAI LA MIGRAZIONE
      migration.runMigration();

      console.log('FINE - popolaTabelleNuove');

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

  },

};

