'use strict';

const Assert = require('assert');
const Joi = require('joi');
const AsteriskManager = require('asterisk-manager');

let ami = null;

const initAMI = () => {
    Assert.ok(!ami, 'tried to double-initialize AMI');

    if (!process.env.AMI_ENABLE) {
        console.log('AMI is disabled, skipping AMI initialization')
    } else {
        if (!process.env.AMI_HOST || !process.env.AMI_USER || !process.env.AMI_PASS) {
            console.warn('Some AMI parameters are missing, skipping AMI initialization')
        } else {
            ami = new AsteriskManager(process.env.AMI_PORT, process.env.AMI_HOST, process.env.AMI_USER, process.env.AMI_PASS, true);
            ami.keepConnected();
            ami.on('error', ev => {
                console.warn('AMI error: ' + ev);
            })
            console.log('AMI initialized');
        }
    }
};

const sendAMIAction = (action, callback) => {
    if (!ami) {
        throw new Error('AMI is not initialized')
    }

    return ami.action(action, callback);
};

module.exports = {
    initAMI: initAMI,
    action: sendAMIAction,

    config: Joi.object({
        AMI_ENABLE: Joi.boolean().optional().default(false),
        AMI_HOST: Joi.alternatives().try(Joi.string().hostname(), Joi.string().ip()).when(
            'AMI_ENABLE', {is: Joi.boolean().valid(true), then: Joi.required(), otherwise: Joi.optional()}),
        AMI_PORT: Joi.number().port().when(
            'AMI_ENABLE', {is: Joi.boolean().valid(true), then: Joi.optional().default(5038), otherwise: Joi.optional()}),
        AMI_USER: Joi.string().min(1).when(
            'AMI_ENABLE', {is: Joi.boolean().valid(true), then: Joi.required(), otherwise: Joi.optional()}),
        AMI_PASS: Joi.string().min(1).when(
            'AMI_ENABLE', {is: Joi.boolean().valid(true), then: Joi.required(), otherwise: Joi.optional()})
    })
};
