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

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

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

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

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

const BachecaSchema = new Schema({
  _id: {
    type: Number,
  },
  descr: {
    type: String,
  },
  idSectorBacheca: [{
    type: Number
  }],
  icon: {
    type: String,
  },
  img: {
    type: String,
  },
});

BachecaSchema.statics.findAllIdApp = async function (idapp) {
  const Bacheca = this;

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

  const res = await Bacheca
    .aggregate(query)
    .then((arrrec) => {
      return arrrec
    })

  return res;

};

BachecaSchema.pre('save', async function (next) {
  if (this.isNew) {
    const myrec = await Bacheca.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();
});



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

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


const Bacheca = mongoose.model('Bacheca', BachecaSchema);

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


module.exports = { Bacheca };
