'use strict';
const httpStatus = require('http-status');
const Sequelize = require('sequelize');
const generateControllers = require('../../core/controllers');
const { buildContext } = require('../../core/controllers');
const speakerService = require('./speaker.service');
const { extractParamsFromRequest, handleErrorResponse, handleResultResponse } = require('../../helpers/controller.helper');


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

const controllerOptions = { MODULE_NAME };
const extraControllers = {
    findSimilar: () => {
        return async (req, res, next) => {
            let params = extractParamsFromRequest(req, res, { includeAll: false, paginate: { limit: 1, page: 1 } });
            
            try {
                const speaker = await speakerService.fetchOne(params, buildContext(req, { scopes: ['includeValues'] }));
                const values = speaker.values.map(function(value) { return value.id });

                const newParams = Object.assign({}, params, {
                    params: undefined,
                    query: {
                        id: { 
                            [Sequelize.Op.ne]: params.params.id 
                        }
                    },
                    includeAll: false, 
                    paginate: { limit: 10, page: 1 }
                });

                const similar = await speakerService.fetchAll(newParams, buildContext(req, { 
                    scopes: [
                        'defaultScope', 'onlyPublished', 'includeMultimedias',
                        { method: ['includeValues', values]}
                    ] 
                }));

                similar.rows.sort(function(item1, item2) { return Math.random() - Math.random() });
                return handleResultResponse(similar.rows, similar.count, params, res);
            } catch (error) {
                console.log(error);
                return handleErrorResponse(_options.MODULE_NAME, 'findSimilar', error, res)
            }
        }
    },
 
};

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

