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');

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

const bookingSchema = new Schema({
  idapp: {
    type: String,
  },
  userId: {
    type: String,
  },
  username: {
    type: String,
  },
  tableType: {
    type: Number,
  },
  id_bookedevent: {
    type: String,
  },
  numpeople: {
    type: Number,
  },
  numpeopleLunch: {
    type: Number,
  },
  numpeopleDinner: {
    type: Number,
  },
  numpeopleDinnerShared: {
    type: Number,
  },
  infoevent: {
    type: String,
  },
  msgbooking: {
    type: String,
  },
  datebooked: {
    type: Date,
  },
  modified: {
    type: Boolean,
    default: false
  },
  booked: {
    type: Boolean,
  },
});

bookingSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
  const Booking = this;

  let myfind = {};
  if (sall === '1')
    myfind = { idapp, booked: true };
  else
    myfind = { userId, idapp, booked: true };

  return Booking.find(myfind).lean();
};


function getUsersByBooking(idapp) {
  const query = [
    {
      $match: { idapp }
    },
    {
      $group: { _id: "$userId" }
    },
    {
      $project: {
        _id: {
          $toString: "$userId"
        }
      }
    },
    {
      $Lookup: {
        from: "users",
        localField: "userId",    // field in my collection
        foreignField: "new ObjectId(_id)",  // field in the 'from' collection
        as: "fromItems"
      }
    },
    {
      $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] },] } }
    },
    { $project: { username: 1, name: 1, surname: 1 } }

  ];
  return query
}


bookingSchema.statics.findAllDistinctByBooking = function (idapp) {
  const Booking = this;

  const query = getUsersByBooking(idapp);

  return Booking.aggregate(query)
    .then(ris => {
      return ris
    });
};


const Booking = mongoose.model('Booking', bookingSchema);

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


module.exports = { Booking };
