 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 producerSchema = new Schema({
  idapp: {
    type: String,
  },
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  referent: {
    type: String,
  },
  username: {
    type: String,
  },
  region: {
    type: String,
  },
  city: {
    type: String,
  },
  img: {
    type: String,
  },
  website: {
    type: String,
  }
});

var Producer = module.exports = mongoose.model('Producer', producerSchema);

module.exports.getFieldsForSearch = function () {
  return [{field: 'name', type: tools.FieldType.string}]
};

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

module.exports.findAllIdApp = async function (idapp) {
  const myfind = { idapp };

  return await Producer.find(myfind).lean();
};

module.exports.getAllProducers = function (query, sort, callback) {
  Producer.find(query, null, sort, callback)
}

module.exports.getProducerByDepartment = function (query,sort, callback) {
  Producer.find(query, null, sort, callback)
}

module.exports.getProducerByCategory = function (query,sort, callback) {
  Producer.find(query, null, sort, callback)
}

module.exports.getProducerByTitle = function (query,sort, callback) {
  Producer.find(query, null, sort, callback)
}

module.exports.filterProducerByDepartment = function (department, callback) {
  let regexp = new RegExp(`^${department}$`, 'i')
  var query = { department: { $regex: regexp } };
  Producer.find(query, callback)
}

module.exports.filterProducerByCategory = function (category, callback) {
  let regexp = new RegExp(`^${category}$`, 'i')
  var query = { category: { $regex: regexp } };
  Producer.find(query, callback);
}

module.exports.filterProducerByTitle = function (title, callback) {
  let regexp = new RegExp(`^${title}$`, 'i')
  var query = { title: { $regex: regexp } };
  Producer.find(query, callback);
}

module.exports.getProducerByID = function (id, callback) {
  Producer.findById(id, callback);
}

// const Producer = mongoose.model('Producer', producerSchema);

// module.exports = { Producer };

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

