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 productSchema = new Schema({
  idapp: {
    type: String,
  },
  active: {
    type: Boolean,
  },
  idProducer: {
    type: String
  },
  idStorehouses: [
    { type: Schema.Types.ObjectId, ref: 'Storehouse' }
  ],
  code: {
    type: String,
  },
  name: {
    type: String,
  },
  description: {
    type: String,
  },
  department: {
    type: String, ref: 'Department'
  },
  category: {
    type: Array,
  },
  prezzo_ivato: {
    type: Number
  },
  perc_iva: {  // 4, 10, 22 &
    type: Number
  },
  price: {
    type: Number
  },
  after_price: {
    type: String
  },
  color: {
    type: String
  },
  size: {
    type: String
  },
  weight: {
    type: Number
  },
  quantityAvailable: {
    type: Number
  },
  quantityLow: {  //Soglia disponibilità bassa
    type: Number
  },
  visibilityProductOutOfStock: {  // Visibilità prodotto "esaurito"
    type: Boolean
  },
  canBeShipped: {  // è spedibile
    type: Boolean
  },
  canBeBuyOnline: {  // è acquistabile online
    type: Boolean
  },
  stars: {
    type: Number
  },
  dateAvailableFrom: {
    type: Date
  },
  icon: {
    type: String,
  },
  img: {
    type: String,
  },
  img2: {
    type: String,
  },
  img3: {
    type: String,
  },
});

var Product = module.exports = mongoose.model('Product', productSchema);

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, code) {
  let myfind = { idapp, active: true };

  if (code) {
    myfind = { ...myfind, code }
  }

  // return await Product.find(myfind);

  const query = [
    { $match: myfind },
    { "$addFields": { "myidProd": { "$toObjectId": "$idProducer" } } },
    {
      $lookup: {
        from: 'producers',
        localField: 'myidProd',
        foreignField: '_id',
        as: 'producer'
      }
    },
    { $unwind: '$producer' },
    {
      $lookup: {
        from: 'storehouses',
        localField: 'idStorehouses',
        foreignField: '_id',
        as: 'storehouses'
      }
    },
  ];

  let ris = await Product.aggregate(query)

  return ris;


};

module.exports.getAllProducts = function (query, sort, callback) {
  Product.find(query, null, sort, callback)
}

module.exports.getProductByDepartment = function (query, sort, callback) {
  Product.find(query, null, sort, callback)
}

module.exports.getProductByCategory = function (query, sort, callback) {
  Product.find(query, null, sort, callback)
}

module.exports.getProductByTitle = function (query, sort, callback) {
  Product.find(query, null, sort, callback)
}

module.exports.getProductByCode = function (idapp, code) {
  return Product.findOne({ idapp, code })
}

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

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

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

module.exports.getProductByID = function (id, callback) {
  Product.findById(id, callback);
}

// const Product = mongoose.model('Product', ProductSchema);

// module.exports = { Product };
