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

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

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

const { Reaction } = require('./reaction');

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

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

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

const MySkillSchema = new Schema(
  {
    ...{
      _id: {
        type: String,
        default: function () {
          return new ObjectID().toString();
        },
      },
      idapp: {
        type: String,
        required: true,
      },
      userId: { type: Schema.Types.ObjectId, ref: 'User' },
      idSector: {
        type: Number,
      },
      idSkill: {
        type: Number,
        default: 0,
      },
      /*idSubSkill: [
        {
          type: Number,
          default: 0,
        }],
    
       */
      idStatusSkill: [
        {
          type: Number,
        }],
      idContribType: [
        {
          type: String,
        }],
      idCity: [
        {
          type: Number,
        }],
      pub_to_share: {
        type: Number,  // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
      },
      numLevel: {
        type: Number,
        default: 0,
      },
      adType: {
        type: Number,
      },
      photos: [
        {
          imagefile: {
            type: String,
          },
          alt: {
            type: String,
          },
          description: {
            type: String,
          },
        }],
      note: {
        type: String,
        default: '',
      },
      descr: {
        type: String,
      },
      //**ADDFIELD_MYSKILL
      website: {
        type: String,
      },
      date_created: {
        type: Date,
      },
      date_updated: {
        type: Date,
      },
    },
    ...Reaction.getFieldsForReactions()
  }, { strict: false });

MySkillSchema.index({ 'idapp': 1 });


MySkillSchema.pre('save', async function (next) {
  if (this.isNew) {
    if (!this.date_created)
      this.date_created = new Date();
  }

  next();
});

MySkillSchema.statics.findAllIdApp = async function (idapp) {
  const MySkill = this;

  const query = [
    { $match: { idapp } },
    { $sort: { descr: 1 } },
  ];

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

};

MySkillSchema.statics.getFieldsForSearch = function () {
  return [];
};

MySkillSchema.statics.getFieldsLastForSearch = function () {
  return [
    { field: 'note', type: tools.FieldType.string },
    { field: 'descr', type: tools.FieldType.string },
    { field: 'recSkill.descr', type: tools.FieldType.string },
    { field: 'myskill.descr', type: tools.FieldType.string },
  ];
};

MySkillSchema.statics.executeQueryTable = function (idapp, params, user) {
  params.fieldsearch = this.getFieldsForSearch();
  params.fieldsearch_last = this.getFieldsLastForSearch();

  const otherparams = {
    lookup1: {
      lk_tab: 'users',
      lk_LF: 'userId',
      lk_FF: '_id',
      lk_as: 'user',
      af_objId_tab: 'myId',
      lk_proj: this.getProject(),
    },
  };

  params = { ...params, ...otherparams };

  return tools.executeQueryTable(this, idapp, params, user);
};

MySkillSchema.statics.getMyRecById = function (idapp, idSkill) {
  const MySkill = this;

  let query = [
    {
      '$match': {
        '_id': idSkill, idapp
      },
    },
    {
      '$sort': {
        'desc': 1,
      },
    },
    {
      '$addFields': {
        'myId1': {
          '$toObjectId': '$userId',
        },
      },
    },
    {
      '$lookup': {
        'from': 'users',
        'localField': 'myId1',
        'foreignField': '_id',
        'as': 'user',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$user',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    {
      '$lookup': {
        'from': 'skills',
        'localField': 'idSkill',
        'foreignField': '_id',
        'as': 'recSkill',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$recSkill',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    {
      '$lookup': {
        'from': 'sectors',
        'localField': 'idSector',
        'foreignField': '_id',
        'as': 'sector',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$sector',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    /*{
      '$lookup': {
        'from': 'subskills',
        'localField': 'idSubSkill',
        'foreignField': '_id',
        'as': 'myskill',
      },
    },

     */
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$myskill',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    {
      '$lookup': {
        'from': 'cities',
        'localField': 'idCity',
        'foreignField': '_id',
        'as': 'mycities',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$mycities',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
  ];

  let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYSKILLS);

  const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
  query = [...query, ...objadd.query];

  const toadd = {
    $project: this.getProject(objadd.proj),
  };

  query = [...query, { ...toadd }];

  return MySkill.aggregate(query).then((rec) => {
    return rec ? rec[0] : null;
  });
};

MySkillSchema.statics.getProject = function (proj_add2) {
  let proj = {
    recSkill: 1,
    sector: 1,
    idSector: 1,
    idSkill: 1,
    idStatusSkill: 1,
    website: 1,
    'numLevel': 1,
    //**ADDFIELD_MYSKILL
  };

  const proj_add = shared_consts.getProjectForAll(proj_add2)

  return Object.assign({}, proj, proj_add);

}

MySkillSchema.statics.getCompleteRecord = function (idapp, id) {
  const MySkill = this;

  return MySkill.getMyRecById(idapp, id);

};

const MySkill = mongoose.model('MySkill', MySkillSchema);

module.exports = { MySkill };
