/* global Events Reservations */
'use strict';

const _ = require('lodash');
const moment = require('moment');
const Sequelize = require('sequelize');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const models = require('../../core/models');
const xlsx = require("node-xlsx");
const fs = require("fs");
const cdnHelper = require('../../helpers/cdn.helper');


const extraMethods = {

    _getReservaById: (Id) => {
        return models.EventReservation.findOne({
            where: { id: Id },
        })
    },

    _getReservaByCode: (eventId, code) => {
        return models.EventReservation.findOne({
            where: { reservation_code: code, eventId: eventId },
            include: [{
                model: models.Event,
            }, {model: models.Entity}],
        })
    },

    _getPartners: (eventId) => {
        return models.EventReservation.findAll({
            where: { eventId: eventId },
            include: [{ model: models.Entity,
                include: [{ model: models.EntityType, as:'types', where:{alias: 'partner'}}],
            }],
            order: [[{ model: models.Entity }, 'name', 'asc']],
        })
    },

    _getColleges: (eventId) => {
        return models.EventReservation.findAll({
            where: { eventId: eventId },
            include: [{
                model: models.Entity,
                include: [{ model: models.EntityType, as: 'types', where: { alias: 'college' } }],
            }],
            order: [[{ model: models.Entity }, 'name', 'asc']],
        })
    },    
    
    _updateConfirmedReservation: (id, confirmed) => {
        return new Promise(function (resolve, reject) {
            models.EventReservation.update(
                {
                    confirmed: confirmed,
                },
                {
                    where: { id: id }
                })
                .then(function (result) {
                    resolve((result[0] === 1));
                })
                .catch(function (error) {
                    reject(error)
                });
        });
    },

    _updateSoldOutReservation: (id, sold_out) => {
        return new Promise(function (resolve, reject) {
            models.EventReservation.update(
                {
                    sold_out: sold_out,
                },
                {
                    where: { id: id }
                })
                .then(function (result) {
                    resolve((result[0] === 1));
                })
                .catch(function (error) {
                    reject(error)
                });
        });
    },

    _getReservationsExcel: (user, eventId, partnerId, type, callback) => {
        console.log('>>>>>>>>>>>>>>>>>>>><consulta con type:', type);
        
        var whereType = {};
        if (type == 'partners') 
            whereType = { alias: 'partner'}
        else if (type == 'colleges') 
            whereType = { alias: 'college' };

        models.EventReservation.findAll({
            where: {
                eventId: eventId,
            },
            include: [{
                model: models.Event,
                attributes: ['id', 'name'],
            }, {
                model: models.Entity,
                include: [{ model: models.EntityType, as: 'types', where: whereType }]
            },
            {
                model: models.EventInscription,
                as: 'inscriptions',
                required: false,
            }],

            order: [
               [{ model: models.Entity}, 'name', 'ASC'],
               ['reservation_code', 'ASC'],
               [{ model: models.EventInscription, as: 'inscriptions'}, 'date', 'ASC']               
            ]

        }).then(function (reservations) {
            if (reservations.length) {
                var data = [];

                data.push(["Congreso: " + reservations[0].Event.name]);
                data.push(["Fecha del listado: " + moment().toString()]);
                data.push([]);
                data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada", "Tipo invitación", "Código", "Partner"]);

                var currentReservation = '';
                var currentPartner = '';
                reservations.forEach(function(reserva) {

                    if (currentPartner != reserva.Entity.name) {
                        currentPartner = reserva.Entity.name;
                        data.push([]);
                        data.push([]);
                    };

                    if (currentReservation != reserva.reservation_code) {
                        currentReservation = reserva.reservation_code;
                        data.push([]);
//                        data.push(["Partner: " + reserva.Entity.name + "  CÓDIGO: " + reserva.reservation_code, "Tipo: " + reserva.description, "Reservadas: " + reserva.confirmed, "Aforo: " + reserva.assistants]);
//
//                        data.push(["Nombre", "Apellidos", "Email", "Válido", "Vía", "N. entrada"]);
                    };

                    reserva.inscriptions.forEach(function (inscription) {
                        data.push([inscription.user.name, inscription.user.surname, inscription.user.email, inscription.validated ? "Confirmado" : "En lista de espera", inscription.source, inscription.code_ticket, reserva.description, reserva.reservation_code, reserva.Entity.name]);
                    });
                });

                var buffer = xlsx.build([{
                    name: reservations[0].Event.name,
                    data: data,
                }], {
                        '!cols': [{ wch: 15 }, { wch: 25 }, { wch: 30 }, { wch: 10 }, { wch: 20 }, { wch: 20 }, { wch: 5 }]
                    });

                var fileName = cdnHelper.sanitizeFilename(reservations[0].Event.name + "-invitaciones.xlsx");
                var xlsxPath = cdnHelper.getCDNPath('xlsx') + fileName;
                var wstream = fs.createWriteStream(xlsxPath);
                wstream.write(buffer);
                wstream.end();

                wstream.on("close", function () {
                    return callback({
                        messenger: {
                            success: true,
                            message: 'Ok',
                            code: 'S99001'
                        },
                        data: {
                            path: xlsxPath,
                            name: fileName
                        }
                    }, 200);
                });
            } else {
                return callback({
                    messenger: {
                        success: true,
                        message: 'Ok',
                        code: 'S99002'
                    }
                }, 200);
            }
        }).catch(function (error) {
            console.log(error);
            return callback({
                messenger: {
                    success: false,
                    message: 'Database error getting invitations.',
                    code: 'E01004'
                }
            }, 500);
        });
    },

    

};

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