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

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

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

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


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

const CashSchema = new Schema({
  idapp: {
    type: String,
  },
  creatorUserId: {
    type: String,
  },
  idCashCategory: {
    type: String
  },
  idSubCashCategory: {
    type: String
  },
  type: {         // CashType: TYPE_IN, TYPE_OUT
    type: Number
  },
  date_created: {
    type: Date
  },
  date_payment: {
    type: Date
  },
  descr: {
    type: String,
  },
  price: {
    type: Number
  },
  quantity: {
    type: Number
  },
  total: {
    type: Number
  },
  fromWalletUserId: {   // walletCommonCash or any Member
    type: String,
  },
  toWalletUserId: {   // walletCommonCash or any Member
    type: String,
  },
  walletStatus: {  // WalletFinalStatusType: None: 0,  InCommonCash: 1, InMyWallet : 2
    type: Number,
  },
  walletTemporaryToUserId: { // WalletCommonCash
    type: String,
  },
  walletCashId: {
    type: String,
  },
  internal: {
    type: Boolean,
    default: false,
  },
  extra: {
    type: Boolean,
    default: false,
  },
  notes: {
    type: String
  },
  confirmed: {
    type: Boolean,
    default: false,
  },
});

var Cash = module.exports = mongoose.model('Cash', CashSchema);

module.exports.getFieldsForSearch = function () {
  return []
};

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 Cash.find(myfind);
};

module.exports.getAllCash = function (query, sort, callback) {
  Cash.find(query, null, sort, callback)
}

module.exports.getCashByUserId = function (userId, sort, callback) {
  Cash.find({ userId }, null, sort, callback)
}


module.exports.getCashByID = function (id, callback) {
  Cash.findById(id, callback);
}

module.exports.createCash = async function (Cash) {
  const CashModel = new Cash(Cash);

  return await CashModel.save(Cash)
    .then((ris) => {
      if (!!ris)
        return ris._id;
      return null;
    });
}


// const Cash = mongoose.model('Cash', CashSchema);

// module.exports = { Cash };
