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 NewstosentSchema = new Schema({
  idapp: {
    type: String,
  },
  label: {
    type: String,
  },
  templemail_str: {
    type: String,
  },
  activate: {
    type: Boolean,
    default: false
  },
  numemail_tot: {
    type: Number,
    default: 0
  },
  numemail_sent: {
    type: Number,
    default: 0
  },
  datetoSent: {
    type: Date
  },
  datestartJob: {
    type: Date
  },
  datefinishJob: {
    type: Date
  },
  lastemailsent_Job: {
    type: Date
  },
  starting_job: {
    type: Boolean,
    default: false
  },
  finish_job: {
    type: Boolean,
    default: false
  },
  processing_job: {
    type: Boolean,
    default: false
  },
  error_job: {
    type: String,
  }
});

NewstosentSchema.statics.getFieldsForSearch = function () {
  return [{ field: 'name', type: tools.FieldType.string },
    { field: 'surname', type: tools.FieldType.string },
    { field: 'email', type: tools.FieldType.string }]
};

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

NewstosentSchema.statics.findNewsletter_To_Send = function (idapp) {
  const Newstosent = this;

  return Newstosent.findOne({
    // datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
    datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
    activate: true,
    starting_job: false,
    processing_job: false,
    finish_job: false,
    idapp
  })
    .sort({ datetoSent: 1 })
    .then((rec) => {
      return (rec) ? rec._doc : null;
    });
};

NewstosentSchema.statics.endJob = async function (id) {
  const Newstosent = this;

  myjobnews = await Newstosent.findOne({ _id: id });
  if (!!myjobnews) {
    myjobnews.datefinishJob = new Date();
    myjobnews.finish_job = true;

    await myjobnews.save()
  }
};

NewstosentSchema.statics.processingJob = async function (id, state) {
  const Newstosent = this;

  myjobnews = await Newstosent.findOne({ _id: id });
  if (!!myjobnews) {
    myjobnews.processing_job = state;

    await myjobnews.save()
  }
};

NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
  const Newstosent = this;


  return Newstosent.findOne({
    datestartJob: { $lt: tools.IncDateNow(0) },
    activate: true,
    starting_job: true,
    finish_job: false,
    processing_job: false,
    lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 15) },
    idapp
  }).then((rec) => {
    // console.log('findNewsletterPending_To_Send', rec);
    return (rec) ? rec._doc : null;
  });
};

NewstosentSchema.statics.findAllIdApp = async function (idapp) {
  const Newstosent = this;

  const myfind = { idapp };

  // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.

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

NewstosentSchema.statics.getlast = async function (idapp) {
  const Newstosent = this;

  try {
    const mydoc = await Newstosent.find({ idapp }).sort({ datestartJob: -1 }).limit(1);
    return mydoc[0]._doc;
  } catch (e) {
    return null
  }
};

NewstosentSchema.statics.isActivated = async function (_id) {
  const Newstosent = this;

  try {
    const mydoc = await Newstosent.findOne({ _id }).lean();
    return (mydoc.activate);
  } catch (e) {
    return false
  }
};


const Newstosent = mongoose.model('Newstosent', NewstosentSchema);

module.exports = { Newstosent };
