/* global Venue */
'use strict';

const _ = require('lodash');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const Sequelize = require('sequelize');
const models = require('../../core/models');
const { speakerComposer } = require('../../helpers/composes.helper');

const extraMethods = {
    afterFetchAll: (result, params, context) => {

        if (!result.count) {
            return result;
        }

        let rows = result.rows.map(row => row.toJSON());
        rows = rows.map(speaker => speakerComposer(speaker, context));

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

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

    beforeUpdate: (values, findOptions, context) => {
        delete values.createdAt;
        delete values.updatedAt;
        delete values.userId;

        // Descomponemos RRSS
        values = Object.assign(values, values.rrss, { rrss: undefined });

        return values;
    },

    update: async (params, values, context) => {
        const findOptions = parseParamsToFindOptions(params);
        if (extraMethods.beforeUpdate) {
            values = extraMethods.beforeUpdate(values, findOptions, context);
        }

        let speaker = await models.Speaker.findOne(findOptions);
        await speaker.update(values);
        speaker.setValues(values.values.map(value => value.id));
        
        await speaker.save();
        return [1];
    },



}

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