'use strict';

const Promise = require('bluebird');
const EventEmitter = require('paradox-utils').EventEmitter;
const __ = require('paradox-utils');
const _ = require('lodash');

class Controller extends EventEmitter {

    /**
     * Se llama siempre antes de llamar a una función.
     *
     * @return {Promise.<T>}
     */
    preload() {
        return Promise.resolve();
    }

    invoke(method, args) {
        return Promise.try(() => {
            if(!(method in this)) {
                throw new Error('method "' + method + '" doesn\'t exists in ' + this.constructor.name);
            }

            let request = args[0];

            let toInject = _.defaults(
                {},
                {request},
                request.params,
                request.query,
                request.body
            );

            return __.reflection.applyMapping(this[method], this, toInject);
        });
    }

    /**
     * Se llama 1 vez si se registra como middleware.
     *
     * @param router
     * @return {Promise.<T>}
     */
    register(router) {
        return Promise.resolve();
    }
}

module.exports = Controller;