const 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 OperatorSchema = new Schema({
  idapp: {
    type: String,
  },
  username: {
    type: String,
  },
  name: {
    type: String,
    trim: true,
  },
  surname: {
    type: String,
    trim: true,
  },
  email: {
    type: String,
    trim: true,
  },
  usertelegram: {
    type: String,
  },
  cell: {
    type: String,
    trim: true,
  },
  img: {
    type: String,
  },
  qualification: {  // President, Vice-President, ecc...
    type: String,
  },
  disciplines: {
    type: String,
  },
  certifications: {
    type: String,
  },
  webpage: {
    type: String,
  },
  days_working: {
    type: String,
  },
  facebook: {
    type: String,
  },
  info: {  // Biografia HTML
    type: String,
  },
  intro: {
    type: String,
  },
  offers: {
    type: String,
  },
  skype: {
    type: String,
  },
  showInTeam: {
    type: Boolean,
  },
  arrDisciplines: [{
    type: String,
  }],
});

OperatorSchema.statics.getEmailByUsername = async function (idapp, username) {
  const Operator = this;

  return await Operator.findOne({ idapp, username })
    .then((arrrec) => {
      return ((arrrec) ? arrrec.email : '');
    }).catch((e) => {
      console.error('getEmailByUsername', e);
    });
};

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


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

OperatorSchema.statics.findAllIdApp = function (idapp) {
  const Operator = this;

  const myfind = { idapp };

  // Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.


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

const Operator = mongoose.model('Operator', OperatorSchema);

module.exports = { Operator };
