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

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

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


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

const CalZoomSchema = new Schema({
  idapp: {
    type: String,
  },
  lang: {
    type: String,
  },
  title: {
    type: String,
  },
  typeconf: {
    type: String,
  },
  icon: {
    type: String,
  },
  color: {
    type: String,
  },
  date_start: {
    type: Date
  },
  benvenuto: {
    type: Boolean
  },
  date_end: {
    type: Date
  },
  id_conf_zoom: {
    type: String
  },
  note: {
    type: String
  }
});

CalZoomSchema.statics.getFieldsForSearch = function () {
  return [{field: 'title', type: tools.FieldType.string}]
};

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

CalZoomSchema.statics.findAllIdApp = async function (idapp) {
  const CalZoom = this;

  const myfind = { idapp, date_start: { $gt: tools.IncDateNow(-1000 * 60 * 60 * 3) } };

  return await CalZoom.find(myfind).sort({ date_start: 1 }).limit(10);
};

CalZoomSchema.statics.getNextZoom = async function (idapp) {
  const CalZoom = this;

  // const myfind = { idapp, $and: [{ date_start: { $gt: tools.IncDateNow(-1000 * 60 * 5) } }, { date_start: { $lt: tools.IncDateNow(1000 * 60 * 60 * 6)  } }] } ;
  const myfind = { idapp, $and: [{ date_start: { $lt: tools.IncDateNow(1000 * 60 * 5) } }, { date_start: { $gt: tools.IncDateNow(-1000 * 60 * 60 * 2)  } }] } ;

  return await CalZoom.findOne(myfind).sort({ date_start: 1 });
};

const CalZoom = mongoose.model('CalZoom', CalZoomSchema);

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


module.exports = { CalZoom };
