'use strict';

const Boom = require('@hapi/boom');
const Joi = require('joi');
const Rfr = require('rfr');

const Calls = Rfr('/server/sections/calls');


const mainHandler = async (request, h) => {
    let options = {
        activeSection: request.params.section
    };

    switch (request.params.section) {
        case 'calls':
            try {
                options.filter = await Calls.getFilter(request.query);
            } catch (e) {
                throw Boom.badRequest(`CDR query failed validation: ${e}`);
            }

            options.cdr = await Calls.getCdr(options.filter);
            options.title = 'Звонки';

            break;
        case 'settings':
            options.title = 'Настройки';
        default:
            break;
    }

    if (!options.pageCard) {
        options.pageCard = options.title;
    }

    return h.view(request.params.section, options);
}

module.exports = {
    routes: [{
        method: 'GET',
        path: '/public/{file*}',
        handler: {
            directory: {
                path: ['./client', './shared']
            }
        }
    },
    {
        method: 'GET',
        path: '/{section?}',
        handler: mainHandler,
        options: {
            validate: {
                params: Joi.object({
                    section: Joi.string().optional().valid('calls', 'reports', 'status', 'settings').default('calls')
                })
            }
        }
    }]
}
