/* global Venue */
"use strict";

const _ = require("lodash");
const moment = require("moment");
const { generateService, parseParamsToFindOptions } = require("../../helpers/service.helper");
const Sequelize = require("sequelize");
const models = require("../../core/models");
const { citiesComposer, eventComposer } = require("../../helpers/composes.helper");

const extraMethods = {
  afterFetchAll: (result, params, context) => {
    if (!result.count) {
      return result;
    }

    let rows = result.rows.map((row) => row.toJSON());

    if (context.scopes.includes("CitiesOfEvents")) rows = rows.map((city) => citiesComposer(city, context));
    else rows = rows.map((event) => eventComposer(event, context));

    return {
      count: result.count,
      rows: rows,
    };
  },

  afterFetchOne: (result, params, context) => {
    if (result) result = result.toJSON();
    return eventComposer(result, context);
  },

  _getEvent: (eventId) => {
    return models.Event.findOne({
      where: {
        id: eventId,
        typeId: { [Sequelize.Op.ne]: null },
      },
    });
  },

  _updateConfirmedEvent: (eventId, confirmed) => {
    return new Promise(function (resolve, reject) {
      models.Event.update(
        {
          confirmed: confirmed,
        },
        {
          where: { id: eventId, typeId: { [Sequelize.Op.ne]: null } },
        }
      )
        .then(function (result) {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateConfirmedEvent", result);
          if (result) resolve(result[0] === 1);
          else resolve(false);
        })
        .catch(function (error) {
          reject(error);
        });
    });
  },

  _updateAssistantsEvent: (eventId, assistants) => {
    console.log('>> _updateAssistantsEvent: Actualizamos aforo', assistants);
    return new Promise(function (resolve, reject) {
      models.Event.update(
        {
          assistants: assistants,
        },
        {
          where: { id: eventId, typeId: { [Sequelize.Op.ne]: null } },
        }
      )
        .then(function (result) {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateAssistantsEvent", result);
          if (result) resolve(result[0] === 1);
          else resolve(false);
        })
        .catch(function (error) {
          reject(error);
        });
    });
  },  

  _updateSoldOutEvent: (eventId, sold_out) => {
    return new Promise(function (resolve, reject) {
      models.Event.update(
        {
          sold_out: sold_out,
        },
        {
          where: { id: eventId },
        }
      )
        .then(function (result) {
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>><resultado _updateSoldOutEvent", result);
          if (result) resolve(result[0] === 1);
          else resolve(false);
        })
        .catch(function (error) {
          reject(error);
        });
    });
  },

  _updateAforoOfEventReservation: async (reservation, cantidad) => {

    //Cogemos el evento del que tenemos que aumentar o disminuir aforo, en funcion de la cantidad si es negativa o positiva
      const eventToUpdateAssistants = reservation.overflow_reservationId
      ? await extraMethods._getEvent(reservation.overflow_reservationId)
      : await extraMethods._getEvent(reservation.eventId);
  
      console.log('_updateAforoOfEventReservation Evento >>>>>>>>>>>>>>>', eventToUpdateAssistants.name);
      console.log('_updateAforoOfEventReservation Asistentes >>>>>>>>>>>>>>>', eventToUpdateAssistants.assistants);    
      console.log('_updateAforoOfEventReservation Aumento en  >>>>>>>>>>>>>>>', cantidad);        

      const plazasDisponibles = eventToUpdateAssistants.assistants - eventToUpdateAssistants.confirmed;
      console.log('_updateAforoOfEventReservation Plazas disponibles >>>>>>>>>>>>>>>', plazasDisponibles);  
                  
      //En caso de cantidad negativa si vamos a permirir aumentar el aforo con la cantidad recuperada
      if ((cantidad >=0) && (plazasDisponibles < cantidad)) {
        console.log ('_updateAforoOfEventReservation >>>> Aforo lleno no es posible efectuar la invitacion');        
        throw new Error ('Aforo lleno no es posible efectuar la invitacion');
      };      

      //Modificamos los asistentes de evento (AFORO)
      const newAforo = eventToUpdateAssistants.assistants - cantidad;        
      if (!(await extraMethods._updateAssistantsEvent(eventToUpdateAssistants.id, newAforo))) {
        console.log("_updateAforoOfEventReservation >>>> No se ha podido actualizar el aforo del evento");
        throw new Error ('No se ha podido actualizar el aforo del evento');        
      };

      //Si se ha llenado ponemos el evento en SOLD_OUT
      if (eventToUpdateAssistants.confirmed >= newAforo)
        await extraMethods._updateSoldOutEvent(eventToUpdateAssistants.id, true); 

      reservation.event = eventToUpdateAssistants;
  },
};

module.exports = generateService(models.Event, extraMethods);
