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

const escapeStringRegexp = require('escape-string-regexp');

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

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

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

const shared_consts = require('../tools/shared_nodejs');

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

const CitySchema = new Schema({
  _id: {
    type: Number,
  },
  istat: {
    type: String,
  },
  comune: {
    type: String,
  },
  prov: {
    type: String,
    maxlength: 3,
  },
  reg: {
    type: String,
    maxlength: 3,
  },
  pref: {
    type: String,
  },
  cap: {
    type: String,
    maxlength: 6,
  },
  abitanti: {
    type: String,
  },
  country: {
    type: String,
    maxlength: 3,
  },
});

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

CitySchema.statics.getProvinceByIdCity = async function(idcity) {
  const myrec = await City.findOne({_id: idcity}).lean();
  if (myrec) {
    return myrec.prov;
  }

  return '';
}

CitySchema.statics.getCircuitNameBystrProv = async function(strProv) {
  const { Circuit } = require('../models/circuit');

  const myrec = await Circuit.findOne({strProv}).lean();
  if (myrec) {
    return myrec.name;
  }

  return '';
}

CitySchema.statics.getRegionByIdCity = async function(idcity) {
  const myrec = await City.findOne({_id: idcity}).lean();
  if (myrec) {
    return myrec.reg;
  }

  return '';
}

CitySchema.statics.findByCity = function(mycity) {

  let myregexp = new RegExp(mycity.trim().replace(' ', '|'), 'ig');

  const query = [
    {$match: {comune: {$regex: myregexp}}},
    {$sort: {descr: 1}},
  ];

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

};

CitySchema.statics.getFieldsForSearch = function() {
  return [
    {field: 'comune', type: tools.FieldType.string},
    {field: 'prov', type: tools.FieldType.string},
    {field: 'reg', type: tools.FieldType.string},
    {field: 'pref', type: tools.FieldType.number},
    {field: 'cap', type: tools.FieldType.number},
  ];
};

CitySchema.statics.executeQueryTable = function(idapp, params) {
  params.fieldsearch = this.getFieldsForSearch();

  const strfind = params.search;

  if (strfind === '') {
    return [];
  }

  return tools.executeQueryTable(this, 0, params);
};

CitySchema.statics.executeQueryPickup = async function(idapp, params) {

  const strfind = params.search;

  if (strfind === '' && !params.filter) {
    return [];
  }

  let filterfindexact = {};
  if (strfind) {
    filterfindexact = {comune: strfind};
  }

  let limit = 10;
  let risexact = [];

  let filterfind = {comune: {$regex: '^' + strfind, $options: 'i'}};

  let aggr1 = [
    {
      $match: {comune: strfind},
    },
    { $limit : 1 },
    {
      $project: {
        comune: { $concat: ["$comune", " (", "$prov", ")"] },
      },
    },
  ];

  if (params.filter) {
    filterfind = {...params.filter, ...filterfind};
    limit = 200;
  } else {
    // risexact = await City.find(filterfindexact, {comune: 1, prov: 1, reg: 1}).lean();
    risexact = await City.aggregate(aggr1);
  }

  let aggr2 = [
    {
      $match: filterfind,
    },
    { $limit : limit },
    {
      $project: {
        comune: { $concat: ["$comune", " (", "$prov", ")"] },
      },
    },
  ];


  // let ris = await City.find(filterfind, {comune: 1, prov: 1, reg: 1}).lean().limit(limit);
  let ris = await City.aggregate(aggr2).limit(limit);

  return [...risexact, ...ris];

};


CitySchema.statics.findAllIdApp = async function(idapp) {
  const myfind = {};

  return await City.find(myfind);
};

const City = mongoose.model('City', CitySchema);

module.exports = {City};
