var BrevisOne = {
    params: [],

    addParam: function (name, value) {
        BrevisOne.params.push(name + '=' + encodeURIComponent(value));
    },

    setProxy: function (HTTPProxy) {
        BrevisOne.HTTPProxy = HTTPProxy;
    },

    setPayload: function (params) {
        var parts = params.send_to.split(':'),
            defaultValues = {
                ring: 'true',
                flash: 'true',
                telauto: 'false'
            };

        BrevisOne.addParam('username', params.username);
        BrevisOne.addParam('password', params.password);
        BrevisOne.addParam('text', params.text);

        if (parts.length > 1) {
            BrevisOne.addParam('mode', parts[0]);
            BrevisOne.addParam('to', parts[1]);
        }
        else {
            BrevisOne.addParam('to', parts[0]);
        }

        Object.keys(defaultValues)
            .forEach(function (key) {
                if (params[key] && params[key].trim() && params[key].toLowerCase() === defaultValues[key]) {
                    BrevisOne.addParam(key, defaultValues[key]);
                }
            });
    },

    request: function () {
        var response,
            request = new HttpRequest(),
            data = '?' + BrevisOne.params.join('&');

        request.addHeader('Content-Type: multipart/form-data');

        if (typeof BrevisOne.HTTPProxy !== 'undefined' && BrevisOne.HTTPProxy !== '') {
            request.setProxy(BrevisOne.HTTPProxy);
        }

        Zabbix.log(4, '[ BrevisOne Webhook ] Sending request.');

        response = request.post(params.endpoint + data);

        Zabbix.log(4, '[ BrevisOne Webhook ] Received response with status code ' +
            request.getStatus() + '\n' + response);

        if (request.getStatus() < 200 || request.getStatus() >= 300) {
            var message = 'Request failed with status code ' + request.getStatus();

            if (response) {
                message += ': ' + response;
            }

            throw message + '. Check debug log for more information.';
        }
    }
};

try {
    var params = JSON.parse(value);

    ['endpoint', 'password', 'username', 'text', 'send_to'].forEach(function (field) {
        if (typeof params !== 'object' || typeof params[field] === 'undefined'
                || !params[field].trim()) {
            throw 'Required parameter is not set: "' + field + '".';
        }
    });

    if (params.send_to === '{ALERT.SENDTO}') {
        throw 'Required parameter is not set: "send_to".';
    }

    BrevisOne.setProxy(params.HTTPProxy);
    BrevisOne.setPayload(params);
    BrevisOne.request();

    return 'OK';
}
catch (error) {
    Zabbix.log(3, '[ BrevisOne Webhook ] ERROR: ' + error);
    throw 'Sending failed: ' + error;
}