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

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

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

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

const sendmsgSchema = new Schema({
  idapp: {
    type: String,
  },
  source: {
    page: { type: String },
    event_id: { type: String },
    infoevent: { type: String }
  },
  origin: {
    type: String,
  },
  dest: {
    type: String,
  },
  message: {
    type: String,
  },
  datemsg: {
    type: Date,
  },
  status: {
    type: Number,
  },
  typesend: {
    type: Number,
  },
  read: {
    type: Boolean,
    default: false
  },
  deleted: {
    type: Boolean,
    default: false
  },

});

sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastdataread, idapp) {
  const SendMsg = this;

  return SendMsg.find({
    $and: [
      { $or: [ { 'dest': username }, { 'origin': username },] },
      { 'datemsg': {$gt: new Date(lastdataread)} },
      { idapp }
    ]
  }).then((arrmsg) => {
    console.log('arrmsg', arrmsg.length);
    return arrmsg
  }).catch((err) => {
    console.error('err', err);
  });

};

sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username, idapp) {
  const SendMsg = this;

  return SendMsg.aggregate([
    {
      $match: {
        $or: [{ 'origin': username }, { 'dest': username }, { idapp }],
        $and: [{ idapp }]
      }
    },
    {
      $group:
        {
          _id: "$dest",
          message: { $last: "$message" },
          datemsg: { $last: "$datemsg" },
          dest: { $last: "$dest" },
          origin: { $last: "$origin" },
          read: { $last: "$read" }
        }

    },
    {
      $sort: { datemsg: -1 }
    },
  ])
    .then((arrmsg) => {
      // Remove duplicate
      // Exclude my chat
      const myarr = arrmsg.filter((ris) => ris._id !== username);
      // console.table(myarr);
      return myarr

    }).catch((err) => {
      console.error(err);
    });

};


const SendMsg = mongoose.model('SendMsg', sendmsgSchema);

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


module.exports = { SendMsg };
