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 CurlHttpRequest(),
            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.Status() + '\n' + response);

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

            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;
}