'use strict';

const moment = require('moment');
const httpStatus = require('http-status');
const generateControllers = require('../../core/controllers');
const eventReservationService = require('./events_reservations.service');
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');
const emailHelper = require('../../helpers/mail.helper');
const path = require("path");


// Module Name
const MODULE_NAME = '[eventReservation.controller]';

const controllerOptions = { MODULE_NAME };

function generateHeaderMail(reservation) {
    let headerMail = null;
    if (reservation) {
        headerMail = {    
            to: reservation.Entity.contact_email,
            name: reservation.Entity.name,
            bcc: "cbarrantes@loquedeverdadimporta.org",
            bccName: "Carolina Barrantes",
            subject: 'Códigos de invitación para congreso LQDVI'
        }
    };
    return headerMail;
}

function generateBodyMail(reservation) {
    let bodyMail = null;
    if (reservation) {
        bodyMail = {
            entityName: reservation.Entity.name,
            eventName: reservation.Event.name,
            dateEvent: moment(reservation.Event.init_date).format('D [de] MMMM [de] YYYY'),
            reservationCode: reservation.reservation_code,
            reservationDescription: reservation.description,
        }
    };
    return bodyMail;
}

const extraControllers = {

    getReservationsExcel: async (req, res, next) => {
        const params = extractParamsFromRequest(req, res, {});
        const eventId = params.params.id;
        const type = params.params.type;
        const userId = req.user.id;

        const reservations = await eventReservationService._getReservationsExcel(req.user, eventId, null, type, function (result, status) {
            if (result.messenger.code == "S99001") {
                console.log(result);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                res.setHeader('Content-Disposition', 'attachment; filename=' + result.data.name);
                res.attachment(result.data.name);
                res.download(path.resolve(result.data.path), result.data.name);
            } else {
                res.status(status).json(result);
            }
        })
    },


    sendMailReservation: async (req, res, next) => {
        const params = extractParamsFromRequest(req, res, {});
        const reservationId = params.params.id;
        const user = req.user;
        try {
            const reservation = await eventReservationService._getReservaByIdWithEntityAndEvent(reservationId);
            if (!reservation)
                return handleResultResponse("Reserva no encontrada", null, params, res, httpStatus.NOT_FOUND);

            try {
                if (reservation.Entity.contact_email)
                    emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
            } catch (error) {
//                console.log(error);
                console.log('No se ha podido mandar email con los códigos de invitación');
            };

            return handleResultResponse(null, null, params, res, httpStatus.OK);

        } catch (error) {
            return handleResultResponse("Error al buscar la reserva", null, params, res, httpStatus.NOT_FOUND);
        }
    },

    sendMailReservationsEvent: async (req, res, next) => {
        const params = extractParamsFromRequest(req, res, {});
        const eventId = params.params.id;
        const entityId = params.params.entityId;            
        const type = params.params.type;    
        const user = req.user;
        let reservations = null;
        let result = "";

        try {
            if (!entityId)
                reservations = await eventReservationService._getReservasByEventAndType(eventId, type);
            else
                reservations = await eventReservationService._getReservasByEventAndEntity(eventId, entityId);

            if (!reservations)
                return handleResultResponse("Reservas no encontradas", null, params, res, httpStatus.NOT_FOUND);

            try {
                reservations.forEach(function (reservation) {
                    console.log('mando correo: ', reservation.Entity.name);
                    if (reservation.Entity.contact_email) {                   
                        emailHelper.sendReservationCode(generateHeaderMail(reservation), generateBodyMail(reservation));
                        result = result + 'Invitación con código ' + reservation.reservation_code + ' enviada a ' + reservation.Entity.name + ' al destinatario ' + reservation.Entity.contact_email + '\n'
                    }
                });
            } catch (error) {
                //                console.log(error);
                console.log('No se ha podido mandar email con los códigos de invitación');
            };

            return handleResultResponse(result, null, params, res, httpStatus.OK);

        } catch (error) {
            return handleResultResponse("Error al buscar las reservas", null, params, res, httpStatus.NOT_FOUND);
        }
    },

};

module.exports = generateControllers(eventReservationService, extraControllers, controllerOptions);

