const mongoose = require('mongoose');
const _ = require('lodash');

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

const { ListaIngresso } = require('./listaingresso');
const { Settings } = require('./settings');
const { User } = require('./user');

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

const shared_consts = require('../tools/shared_nodejs');

mongoose.Promise = global.Promise;

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

mongoose.set('debug', process.env.DEBUG);


const NavePersistenteSchema = new mongoose.Schema({
  idapp: {
    type: String,
    required: true,
  },
  index: {
    type: Number
  },
  riga: {
    type: Number,
  },
  col: {
    type: Number,
  },
  riga1don: {
    type: Number,
  },
  col1don: {
    type: Number,
  },
  date_start: {
    type: Date
  },
  date_gift_chat_open: {
    type: Date
  },
  link_chat: {
    type: String,
  },
  provvisoria: {
    type: Boolean,
  },
  DoniAttesaDiConferma: {
    type: Number,
  },
  DoniMancanti: {
    type: Number,
  },
  DoniConfermati: {
    type: Number,
  },
  DoniTotali: {
    type: Number,
  },
  note_bot: {
    type: String
  },
  note_interne: {
    type: String
  },
  tutor: {
    type: String
  },
  tutor_namesurname: {
    type: String
  }
});

function getQueryProj(myfilter) {

  myobjField = {
    _id: 1,
    idapp: 1,
    lang: 1,
    ind_order: 1,
    name: 1,
    surname: 1,
    username: 1,
    'profile.paymenttypes': 1,
    'profile.email_paypal': 1,
    'profile.cell': 1,
    made_gift: 1,
    sent_msg_howto_make_gift: 1,
    date_made_gift: 1,
    note: 1,
    received_gift: 1,
    date_received_gift: 1,
    num_tess: 1,
    parent_id: 1,
    riga: 1,
    col: 1,
    created: 1,
    // date_start: 1,
    // date_gift_chat_open: 1,
    // link_chat: 1,
    // provvisoria: 1,
    // note_bot: 1,
    // note_interne: 1,
    // tutor: 1,
    // tutor_namesurname: 1,
  };

  const query = [
    { $match: myfilter },
    {
      $lookup: {
        from: "listaingressos",
        localField: "ind_order",
        foreignField: "ind_order",      // field in the user collection
        as: "mylista"
      }
    },
    {
      $unwind: "$mylista"
    },
    {
      $lookup: {
        from: "users",
        as: "user",
        let: {username: '$mylista.username' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ['$username', '$$username'] },
                  { $eq: ['$idapp', myfilter.idapp] },
                ]
              }
            }
          }
        ]
      }
    },
    {
      $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } }
      // $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] },] } }
    },
    { $project: myobjField }
  ];

  return query;
}


NavePersistenteSchema.statics.findById = function (idapp, id) {
  const NavePersistente = this;

  const myquery = getQueryProj({ idapp, '_id': ObjectID(id) });

  return NavePersistente.aggregate(myquery);

};

NavePersistenteSchema.statics.getFieldsForSearch = function () {
  return [{ field: 'ind_order', type: tools.FieldType.number },
    { field: 'col', type: tools.FieldType.number }]
};

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

NavePersistenteSchema.statics.findAllIdApp = function (idapp) {
  const NavePersistente = this;

  const myfind = { idapp };

  return NavePersistente.find(myfind).sort({ riga: 1, col: 1 });
};

NavePersistenteSchema.statics.getListaNavi = function (idapp) {
  const NavePersistente = this;

  const myfind = { idapp };

  return NavePersistente.find(myfind,
    {
      index: 1,
      riga: 1,
      col: 1,
      riga1don: 1,
      col1don: 1,
      date_start: 1,
      provvisoria: 1,
      DoniConfermati: 1,
      DoniTotali: 1,
      DoniMancanti: 1,
    }
  ).sort({ riga: 1, col: 1 });
};

NavePersistenteSchema.statics.getLastNave = function (idapp) {
  const NavePersistente = this;

  const myfind = { idapp, date_start: { $lte: tools.IncDateNow(0) }, provvisoria: false  };

  return NavePersistente.findOne(myfind,
    {
      index: 1,
      riga: 1,
      col: 1,
      riga1don: 1,
      col1don: 1,
      date_start: 1,
      provvisoria: 1,
      DoniConfermati: 1,
      DoniTotali: 1,
      DoniMancanti: 1,
    }
  ).sort({ riga: -1, col: -1 }).limit(1);
};

NavePersistenteSchema.statics.findByRigaColByDonatore = function (idapp, riga, col, offset) {
  const NavePersistente = this;

  mypos = {
    riga,
    col,
    numup: 3 + offset,
  };
  tools.getRigaColByPosUp(mypos);

  return NavePersistente.findOne({ idapp, riga: mypos.riga, col: mypos.col });

};

NavePersistenteSchema.statics.findByRigaCol = function (idapp, riga, col) {
  const NavePersistente = this;

  return NavePersistente.findOne({ idapp, riga, col });

};


NavePersistenteSchema.statics.getLastRigaCol = async function (idapp) {
  return NavePersistente.findOne({ idapp }).sort({ _id: -1 });
};

NavePersistenteSchema.pre('save', async function (next) {
  if (this.isNew) {
    const myrec = await NavePersistente.findOne().limit(1).sort({ _id: -1 });
    if (!!myrec) {
      this.index = myrec._doc.index + 1;
    } else {
      this.index = 1;
    }
  }

  next();
});


NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function (params) {

  // Check if Exist:
  const giapresente = await NavePersistente.findOne({
    idapp: params.idapp,
    riga: params.riga,
    col: params.col
  });

  if (!giapresente) {
    let myNavePersistente = new NavePersistente({
      idapp: params.idapp,
      riga: params.riga,
      col: params.col,
      riga1don: params.riga1don,
      col1don: params.col1don,
      date_start: params.date_start,
      date_gift_chat_open: params.date_gift_chat_open,
      provvisoria: true,
    });
    return await myNavePersistente.save();
  }

  return false;
};


const NavePersistente = mongoose.model('NavePersistente', NavePersistenteSchema);

module.exports = { NavePersistente };


