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

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

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

const {ObjectId} = require('mongodb');

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

const AdTypeGoodSchema = new Schema({
  _id: {
    type: Number,
  },
  descr: {
    type: String,
  },
});

AdTypeGoodSchema.pre('save', async function (next) {
  if (this.isNew) {
    const myrec = await AdTypeGood.findOne().limit(1).sort({_id:-1});
    if (!!myrec) {
      if (myrec._doc._id === 0)
        this._id = 1;
      else
        this._id = myrec._doc._id + 1;
    } else {
      this._id = 1;
    }
  }

  next();
});


AdTypeGoodSchema.statics.findAllIdApp = async function(idapp) {
  const AdTypeGood = this;

  const query = [
    {$sort: {_id: 1}},
  ];

  return await AdTypeGood.aggregate(query).then((arrrec) => {
    return arrrec;
  });

};

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

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

const AdTypeGood = mongoose.model('AdTypeGood', AdTypeGoodSchema);

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


module.exports = {AdTypeGood};
