/* 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)
                });
        });
    },

    _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)
                });
        });
    },

};

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