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

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

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

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

const {Settings} = require('./settings');

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

const MyEventSchema = new Schema({
  idapp: {
    type: String,
  },
  typol: {
    type: String,
  },
  short_tit: {
    type: String,
  },
  title: {
    type: String,
  },
  details: {
    type: String,
  },
  bodytext: {
    type: String,
  },
  dateTimeStart: {
    type: Date,
  },
  dateTimeEnd: {
    type: Date,
  },
  bgcolor: {
    type: String,
  },
  icon: {
    type: String,
  },
  img_small: {
    type: String,
  },
  img: {
    type: String,
  },
  wherecode: {
    type: String,
  },
  contribtype: {
    type: String,
  },
  price: {
    type: Number,
  },
  infoafterprice: {
    type: String,
  },
  teacher: {
    type: String,
  },
  teacher2: {
    type: String,
  },
  teacher3: {
    type: String,
  },
  teacher4: {
    type: String,
  },
  infoextra: {
    type: String,
  },
  linkpage: {
    type: String,
  },
  linkpdf: {
    type: String,
  },
  nobookable: {
    type: Boolean,
  },
  news: {
    type: Boolean,
  },
  canceled: {
    type: Boolean,
  },
  lunchAvailable: {
    type: Boolean,
  },
  dinnerAvailable: {
    type: Boolean,
  },
  dinnerSharedAvailable: {
    type: Boolean,
  },
  lunchType: {
    type: Number,
  },
  dinnerType: {
    type: Number,
  },
  lunchPrice: {
    type: Number,
  },
  dinnerPrice: {
    type: Number,
  },
  internal: {
    type: Boolean,
  },
  note: {
    type: String,
  },
  pagefooter: [
    {
      type: String,
    }],
  deleted: {
    type: Boolean,
  },
  dupId: {
    type: mongoose.Schema.Types.ObjectId,
  },
  facebook: {
    type: String,
  },
  modified: {
    type: Boolean,
  },
});

MyEventSchema.statics.findAllIdApp = async function(socioresidente, idapp) {
  const Event = this;

  let query = [];

  if (socioresidente) {
    query = [
      {
        $match: {
          idapp,
          $or: [
            {deleted: {$exists: false}},
            {deleted: {$exists: true, $eq: false}}],
        },
      },
    ];
  } else {
    query = [
      {
        $match: {
          idapp,
          $and: [
            {
              $or: [
                {deleted: {$exists: false}},
                {deleted: {$exists: true, $eq: false}},
              ],
            },
            {
              $or: [
                {internal: {$exists: false}},
                {internal: {$exists: true, $eq: false}}],
            },
          ],
        },
      },
    ];
  }

  query.push({$sort: {dateTimeStart: 1}});

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

};

MyEventSchema.statics.getLastEvents = async function(idapp) {
  const Event = this;

  const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_EV', 1);

  const query = [
    {
      $match: {
        idapp,
        dateTimeStart: {$gte: tools.IncDateNow(-1000 * 60 * 60 * 24)},
        $or: [
          {deleted: {$exists: false}},
          {deleted: {$exists: true, $eq: false}}],
      },
    },
    {
      $lookup: {
        from: 'operators',
        localField: 'teacher',
        foreignField: 'username',
        as: 'op1',
      },
    },
    {
      $lookup: {
        from: 'operators',
        localField: 'teacher2',
        foreignField: 'username',
        as: 'op2',
      },
    },
    {
      $lookup: {
        from: 'operators',
        localField: 'teacher3',
        foreignField: 'username',
        as: 'op3',
      },
    },
    {
      $lookup: {
        from: 'operators',
        localField: 'teacher4',
        foreignField: 'username',
        as: 'op4',
      },
    },
    {'$addFields': {'contribtype': {'$toObjectId': '$contribtype'}}},
    {
      $lookup: {
        from: 'contribtypes',
        localField: 'contribtype',
        foreignField: '_id',
        as: 'contrib',
      },
    },
    {$sort: {dateTimeStart: 1}},
  ];

  return Event.aggregate(query).then((arrrec) => {
    // console.table(arrrec);
    if (lastn > 0) {
      return arrrec.slice(0, lastn);
    } else {
      return arrrec;
    }
  });

};

MyEventSchema.statics.getFieldsForSearch = function() {
  return [
    {field: 'short_tit', type: tools.FieldType.string},
    {field: 'title', type: tools.FieldType.string},
    {field: 'teacher', type: tools.FieldType.string},
    {field: 'details', type: tools.FieldType.string}];
};

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

if (tools.INITDB_FIRSTIME) {
  // console.log('   createIndex MyEvent Index...');
  // MyEventSchema.index({ short_tit: 'text', title: 'text', teacher: 'text', details: 'text' });
}

const MyEvent = mongoose.model('MyEvent', MyEventSchema);

module.exports = {MyEvent};
