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 AccountSchema = new Schema({
  _id: {
    type: Number,
  },
  circuitId: {
    type: Number,
  },
  userId: {
    type: String,
  },
  name: {
    type: String,
  },
  deperibile: {
    type: Boolean,
  },
  importo_iniziale: {
    type: Number,
  },
  saldo: {
    type: Number,
  },
});

AccountSchema.statics.findAllIdApp = async function(idapp) {
  const MyAccount = this;

  const myfind = {idapp};

  return await MyAccount.find(myfind, (err, arrrec) => {
    return arrrec;
  });
};

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

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

};

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

const Account = mongoose.model('Account', AccountSchema);

module.exports = {Account};
