var bcrypt = require('bcryptjs');
const mongoose = require('mongoose').set('debug', false)
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');

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

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

mongoose.Promise = global.Promise;

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

mongoose.set('debug', false);

var ExtraListSchema = new mongoose.Schema({
  idapp: {
    type: String,
    required: true,
  },
  ind_order: {
    type: Number,
  },
  date_reg: {
    type: Date,
  },
  name_complete: {
    type: String,
    trim: true,
  },
  username: {
    type: String,
  },
  name: {
    type: String,
    trim: true,
  },
  surname: {
    type: String,
    trim: true,
  },
  num_invitati: {
    type: Number,
  },
  is_in_whatsapp: {
    type: Boolean,
  },
  is_in_telegram: {
    type: Boolean,
  },
  is_staff: {
    type: Boolean,
  },
  cell_complete: {
    type: String
  },
  nationality: {
    type: String
  },
  saw_zoom_presentation: {
    type: Boolean
  },
  aportador_solidario_name_surname: {
    type: String,
  },
  aportador_solidario_ind_order: {
    type: Number,
  },
  aportador_solidario_originale_name_surname: {
    type: String,
  },
  note: {
    type: String,
  },
  contacted: {
    type: Boolean,
  },
  col_b: {
    type: Number,
  },
  col_h: {
    type: Number,
  },
  registered: {
    type: Boolean,
    default: false
  },

});

// ExtraListSchema.methods.toJSON = function () {
//   const extralist = this;
//   const userObject = extralist.toObject();
//
//   return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
// };
//
ExtraListSchema.statics.findByUsername = function (idapp, username) {
  const ExtraList = this;

  return ExtraList.findOne({
    'idapp': idapp,
    'username': username,
  });
};

ExtraListSchema.statics.getTotInLista = async function (idapp) {
  const ExtraList = this;

  const myfind = { idapp };

  return await ExtraList.countDocuments(myfind);
};

ExtraListSchema.statics.getRegDellaLista = async function (idapp) {
  const ExtraList = this;

  const myfind = { idapp, registered: true };

  return await ExtraList.countDocuments(myfind);
};

ExtraListSchema.statics.getLastUser = function (idapp) {
  const ExtraList = this;

  return ExtraList.findOne({ idapp }).sort({ ind_order: -1 })
};


ExtraListSchema.statics.findByCellAndNameSurname = function (idapp, cell_complete, name, surname) {
  const ExtraList = this;

  return ExtraList.findOne({
    'idapp': idapp,
    'cell_complete': cell_complete,
    'name': name,
    'surname': surname,
  });
};

ExtraListSchema.statics.findByIndOrder = function (idapp, ind_order) {
  const ExtraList = this;

  try {
    return ExtraList.findOne({
      'idapp': idapp,
      'ind_order': ind_order,
    });
  } catch (e) {

  }
};


ExtraListSchema.statics.getUsersList = function (idapp) {
  const User = this;

  return User.find({ 'idapp': idapp }, {
    username: 1,
    name: 1,
    surname: 1,
lasttimeonline: 1,
    date_reg: 1,
  })

};

// ExtraListSchema.statics.getDownlineNotRegisteredByNameSurname = function (idapp, nameandsurname) {
//   const ExtraList = this;
//
//   return ExtraList.find({
//     'aportador_solidario_name_surname': nameandsurname,
//     registered: false,
//   }, {
//     ind_order: 1,
//     name: 1,
//     surname: 1,
//     cell_complete: 1,
//     num_invitati: 1,
//     nationality: 1,
//   }, (err, arrrec) => {
//     return arrrec
//   });
// };

// ExtraListSchema.statics.getUserNotRegisteredByNameSurname = function (idapp, nameandsurname) {
//   const ExtraList = this;
//
//   return ExtraList.findOne({
//     name_complete: nameandsurname,
//     registered: false,
//   }, {
//     lang: 1,
//     ind_order: 1,
//     name: 1,
//     surname: 1,
//     cell_complete: 1,
//     num_invitati: 1,
//     nationality: 1,
//   }, (err, arrrec) => {
//     return arrrec
//   });
// };
//

ExtraListSchema.statics.getFieldsForSearch = function () {
  return [
    { field: 'username', type: tools.FieldType.string },
    { field: 'name', type: tools.FieldType.string },
    { field: 'surname', type: tools.FieldType.string },
    { field: 'cell_complete', type: tools.FieldType.string },
    { field: 'aportador_solidario_name_surname', type: tools.FieldType.string },
    { field: 'aportador_solidario_originale_name_surname', type: tools.FieldType.string }]
};

ExtraListSchema.statics.executeQueryTable = function (idapp, params) {
  params.fieldsearch = this.getFieldsForSearch();
  return tools.executeQueryTable(this, idapp, params);
};

ExtraListSchema.statics.findAllIdApp = async function (idapp) {
  const ExtraList = this;

  const myfind = { idapp };

  return await ExtraList.find(myfind, (err, arrrec) => {
    return arrrec
  });
};

ExtraListSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {

  return await tools.DuplicateAllRecords(this, idapporig, idappdest);

};


/*
ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {

  const ExtraList = this;

  try {
    let numadded = 0;
    let numtot = 0;
    let numalreadyexisted = 0;

    // Convert to array
    let arrusers = strdata.split('\n');
    let sep = ',';

    // console.log('arrusers', arrusers);

    try {
      for (const row of arrusers) {
        console.log('row', row);
        if (sep !== '' && row !== '') {
          let col = row.split(sep);
          if (col) {
            if (col.length > 11) {
              let user = null;
              try {
                user = new ExtraList({
                  idapp: idapp,
                  ind_order: col[0],
                  name_complete: col[2].trim(),
                  num_invitati: col[3].trim(),
                  is_in_whatsapp: col[4].trim() !== '',
                  is_in_telegram: col[5].trim() !== '',
                  is_staff: col[5].trim() === 'VV',
                  saw_zoom_presentation: col[6].trim() !== '',
                  cell_complete: col[7].trim(),
                  nationality: col[8].trim(),
                  aportador_solidario_name_surname: col[9].trim(),
                  aportador_solidario_ind_order: col[10].trim(),
                  aportador_solidario_originale_name_surname: col[11].trim(),
                  note: col[12].trim(),
                  col_b: col[13].trim(),
                  col_h: col[14].trim()
                });

                try {
                  user.date_reg = col[1];
                } catch (e) {
                  console.log('error ', e);
                }

                if (user.cell_complete[0] !== '+')
                  user.cell_complete = '+' + user.cell_complete;

                namesurname = tools.extractNameAndSurnameByComplete(user.name_complete);
                user.name = namesurname.name;
                user.surname = namesurname.surname;

                if (user.name && user.surname && user.cell_complete) {
                  // Save into db
                  await user.save();
                  numadded++;
                }

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

              numtot++;
            }
            // numalreadyexisted++;
          }
        }
      }

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

    ris = { numadded, numtot, numalreadyexisted };

    console.log(ris);
    return ris

  } catch (e) {
    console.err(e);
  }
};
*/


const ExtraList = mongoose.model('ExtraList', ExtraListSchema);


module.exports = { ExtraList };


