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 { MyGroup } = require('./mygroup');

const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');

const tableModel = shared_consts.TABLES_MYHOSPS;

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

const MyHospSchema = new Schema({
  ...{
    _id: {
      type: String,
    },
    idapp: {
      type: String,
      required: true,
    },
    userId: { type: Schema.Types.ObjectId, ref: 'User' },
    groupname: { type: String },
    visibile: {
      type: Boolean
    },
    adType: {
      type: Number,
    },
    typeHosp: {  // scambio casa / ospitalità
      type: Number,
    },
    numMaxPeopleHosp: {
      type: Number,
    },
    accomodation: [
      {
        type: {  // Letto matrimoniale / letto singolo / divano-letto / almaca / a terra sul tappeto (per sacco a pelo) / culla
          type: Number,
        },
        location: {  // in camera privata / in camera condivisa / in soggiorno / in camper / in tenda / in giardino / all'aperto
          type: Number,
        },
        num: {
          type: Number,
        },
      }],
    preferences: [  // Accetto bambini, Accetto cani, Accetto gatti, E' consentito fumare in casa, Accessibile con sedia a rotelle
      {
        type: Number,
      }],
    photos: [
      {
        imagefile: {
          type: String,
        },
        alt: {
          type: String,
        },
        description: {
          type: String,
        },
      }],
    idContribType: [
      {
        type: String,
      }],
    idCity: [
      {
        type: Number,
      }],
    pub_to_share: {
      type: Number,  // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
    },
    descr: {
      type: String,
    },
    note: {
      type: String,
      default: '',
    },
    website: {
      type: String,
    },
    link_maplocation: {
      type: String,
    },
    date_created: {
      type: Date,
      default: Date.now,
    },
    date_updated: {
      type: Date,
    },
  },
  ...Reaction.getFieldsForReactions(),
  ...tools.getFieldsForAnnunci()
});

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

  next();
});

MyHospSchema.statics.findAllIdApp = async function (idapp) {
  const MyHosp = this;

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

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

};

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

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

MyHospSchema.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: shared_consts.getProjectForAll({}, tableModel),
    },
  };

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

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

MyHospSchema.statics.getMyRecById = function (idapp, id) {
  const MyHosp = this;

  const myparsid = { '_id': id, 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: shared_consts.getProjectForAll({}, tableModel),
    },
    {
      '$lookup': {
        'from': 'skills',
        'localField': 'idSkill',
        'foreignField': '_id',
        'as': 'recSkill',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$recSkill',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: shared_consts.getProjectForAll({}, tableModel),
    },
    {
      '$lookup': {
        'from': 'sectors',
        'localField': 'idSector',
        'foreignField': '_id',
        'as': 'sector',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$sector',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $lookup: {
        'from': 'mygroups',
        'localField': 'groupname',
        'foreignField': 'groupname',
        'as': 'mygrp',
      },
    },
    {
      $unwind: {
        path: '$mygrp',
        preserveNullAndEmptyArrays: true,
      },
    },
    {
      $project: shared_consts.getProjectForAll({}, tableModel),
    },
    /*{
      '$lookup': {
        'from': 'subskills',
        'localField': 'idSubSkill',
        'foreignField': '_id',
        'as': 'MyHosp',
      },
    },*/
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$MyHosp',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
    {
      $project: shared_consts.getProjectForAll({}, tableModel),
    },
    {
      '$lookup': {
        'from': 'cities',
        'localField': 'idCity',
        'foreignField': '_id',
        'as': 'mycities',
      },
    },
    {
      '$replaceRoot': {
        'newRoot': {
          '$mergeObjects': [
            {
              '$arrayElemAt': [
                '$mycities',
                0,
              ],
            },
            '$$ROOT',
          ],
        },
      },
    },
  ];

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

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

  const toadd = {
    $project: shared_consts.getProjectForAll(objadd.proj, tableModel),
  };

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

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

MyHospSchema.statics.getCompleteRecord = function (idapp, id) {
  const MyHosp = this;

  return MyHosp.getMyRecById(idapp, id);

};

MyHospSchema.statics.SettaAdTypeOffro_In_Hosps = async function () {
  const MyHosp = this;

  try {
    // Set all records 'adType' to shared_consts.AdType.OFFRO
    const result = await MyHosp.updateMany({}, { $set: { adType: shared_consts.AdType.OFFRO } });
    console.log('Successfully updated adType for', result.modifiedCount, 'records');
  } catch (err) {
    console.error('Error updating adType:', err);
  }
};

/*MyHospSchema.statics.getProject = function () {
  let proj = {
    visibile: 1,
    typeHosp: 1,
    numMaxPeopleHosp: 1,
    accomodation: 1,
    preferences: 1,
    photos: 1,
    website: 1,
    link_maplocation: 1,
    //**ADDFIELD_MYHOSP

  };

  const proj_add = shared_consts.getProjectForAll()

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

}
*/

const MyHosp = mongoose.model('MyHosp', MyHospSchema);

MyHosp.createIndexes()
  .then(() => { })
  .catch((err) => { throw err; });


module.exports = { MyHosp };
