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 MyGoodSchema = new Schema({
  ...{
    _id: {
      type: String,
    },
    idapp: {
      type: String,
      required: true,
    },
    userId: { type: Schema.Types.ObjectId, ref: 'User' },
    idSectorGood: {
      type: Number,
    },
    idGood: {
      type: Number,
      default: 0,
    },
    idShipping: [
      {
        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,
    },
    otherfilters: [{
      type: Number,
    }],
    photos: [
      {
        imagefile: {
          type: String,
        },
        alt: {
          type: String,
        },
        description: {
          type: String,
        },
      }],
    note: {
      type: String,
      default: '',
    },
    descr: {
      type: String,
    },
    //**ADDFIELD_MyGood
    website: {
      type: String,
    },
    date_created: {
      type: Date,
    },
    date_updated: {
      type: Date,
    },
  }, 
  ...Reaction.getFieldsForReactions()
});

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

  next();
});

MyGoodSchema.statics.findAllIdApp = async function (idapp) {
  const MyGood = this;

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

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

};

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

MyGoodSchema.statics.getFieldsLastForSearch = function () {
  return [
    { field: 'note', type: tools.FieldType.string },
    { field: 'descr', type: tools.FieldType.string },
    { field: 'recGood.descr', type: tools.FieldType.string },
    { field: 'MyGood.descr', type: tools.FieldType.string },
  ];
};


MyGoodSchema.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);
};

MyGoodSchema.statics.getMyRecById = function (idapp, idGood) {
  const MyGood = this;

  let myparsid = {
    '_id': idGood,
    idapp,
  };

  let query = [
    {
      '$match':
        myparsid,
    },
    {
      '$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': 'goods',
        'localField': 'idGood',
        'foreignField': '_id',
        'as': 'recGood',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$recGood',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    {
      '$lookup': {
        'from': 'sectorgoods',
        'localField': 'idSectorGood',
        // 'localField': 'recGood.idSectorGood',
        'foreignField': '_id',
        'as': 'sectorGood',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$sectorgood',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: this.getProject(),
    },
    {
      '$lookup': {
        'from': 'subgoods',
        'localField': 'idShipping',
        'foreignField': '_id',
        'as': 'MyGood',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$MyGood',
                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_MYGOODS);

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

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

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

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

MyGoodSchema.statics.getCompleteRecord = function (idapp, id) {
  const MyGood = this;

  return MyGood.getMyRecById(idapp, id);

};

MyGoodSchema.statics.getProject = function () {
  let proj = {
    'recGood': 1,
    'sectorGood': 1,
    'idSectorGood': 1,
    'idGood': 1,
    'idShipping': 1,
    'idStatusGood': 1,
    //**ADDFIELD_MYGOOD

  };

  const proj_add = shared_consts.getProjectForAll()

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

}

const MyGood = mongoose.model('MyGood', MyGoodSchema);

module.exports = { MyGood };
