var AwsRds = {
    params: {},

    setParams: function (params) {
        ['access_key', 'secret_key', 'region', 'db_instance_id'].forEach(function (field) {
            if (typeof params !== 'object' || typeof params[field] === 'undefined' || params[field] === '') {
                throw 'Required param is not set: "' + field + '".';
            }
        });

        AwsRds.params = params;
    },

    sign: function (key, message) {
        var hex = hmac('sha256', key, message);

        if ((hex.length % 2) === 1) {
            throw 'Invalid length of a hex string!';
        }

        var result = new Int8Array(hex.length / 2);
        for (var i = 0, b = 0; i < hex.length; i += 2, b++) {
            result[b] = parseInt(hex.substring(i, i + 2), 16);
        }

        return result;
    },

    prepareParams: function (params) {
        var result = [];

        Object.keys(params).sort().forEach(function (key) {
            if (typeof params[key] !== 'object') {
                result.push(key + '=' + encodeURIComponent(params[key]));
            }
            else {
                result.push(prepareObject(key, params[key]));
            }
        });

        return result.join('&');
    },

    request: function (method, region, service, params, data) {
        if (typeof data === 'undefined' || data === null) {
            data = '';
        }

        var amzdate = (new Date()).toISOString().replace(/\\.\\d+Z/, 'Z').replace(/[-:]/g, ''),
            date = amzdate.replace(/T\\d+Z/, ''),
            host = service + '.' + region + '.amazonaws.com',
            canonical_uri = '/',
            canonical_headers = 'content-encoding:amz-1.0\\n' + 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n',
            signed_headers = 'content-encoding;host;x-amz-date',
            canonical_request = method + '\\n' + canonical_uri + '\\n' + params + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + sha256(data),
            credential_scope = date + '/' + region + '/' + service + '/' + 'aws4_request',
            request_string = 'AWS4-HMAC-SHA256' + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + sha256(canonical_request),
            key = AwsRds.sign('AWS4' + AwsRds.params.secret_key, date);

        key = AwsRds.sign(key, region);
        key = AwsRds.sign(key, service);
        key = AwsRds.sign(key, 'aws4_request');

        var request = new HttpRequest(),
            url = 'https://' + host + canonical_uri + '?' + params;

        if (typeof AwsRds.params.proxy !== 'undefined' && AwsRds.params.proxy !== '') {
            request.setProxy(AwsRds.params.proxy);
        }
        request.addHeader('x-amz-date: ' + amzdate);
        request.addHeader('Accept: application/json');
        request.addHeader('Content-Type: application/json');
        request.addHeader('Content-Encoding: amz-1.0');
        request.addHeader('Authorization: ' + 'AWS4-HMAC-SHA256 Credential=' + AwsRds.params.access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + hmac('sha256', key, request_string));

        Zabbix.log(4, '[ AWS RDS ] Sending request: ' + url);

        response = request.get(url);

        Zabbix.log(4, '[ AWS RDS ] Received response with status code ' + request.getStatus() + ': ' + response);

        if (request.getStatus() !== 200) {
            throw 'Request failed with status code ' + request.getStatus() + ': ' + response;
        }

        if (response[0] === '<') {
            try {
                response = XML.toJson(response);
            }
            catch (error) {
                throw 'Failed to parse response received from AWS RDS API. Check debug log for more information.';
            }
        }

        if (response !== null) {
            try {
                response = JSON.parse(response);
            }
            catch (error) {
                throw 'Failed to parse response received from AWS RDS API. Check debug log for more information.';
            }
        }

        return response;
    },

    getEvents: function () {
        var payload = {},
            result = [];

        payload['Action'] = 'DescribeEvents';
        payload['MaxRecords'] = 100;
        payload['Version'] = '2014-09-01';
        payload['Duration'] = 30;
        payload['SourceType'] = 'db-instance';
        payload['SourceIdentifier'] = AwsRds.params.db_instance_id;

        while (payload.NextToken !== '') {
            var events = AwsRds.request('GET', AwsRds.params.region, 'rds', AwsRds.prepareParams(payload));

            if (typeof events !== 'object'
                || typeof events.DescribeEventsResponse !== 'object'
                || typeof events.DescribeEventsResponse.DescribeEventsResult !== 'object'
                || typeof events.DescribeEventsResponse.DescribeEventsResult.Events !== 'object') {
                throw 'Cannot get events from AWS RDS API. Check debug log for more information.';
            }

            if (!Array.isArray(events.DescribeEventsResponse.DescribeEventsResult.Events))
                events.DescribeEventsResponse.DescribeEventsResult.Events = [events.DescribeEventsResponse.DescribeEventsResult.Events]
            events.DescribeEventsResponse.DescribeEventsResult.Events.forEach(function (event) {
                event.EventCategories = event.EventCategories.toString()
                result.push(event)
            });
            payload.NextToken = events.DescribeEventsResponse.DescribeEventsResult.NextToken || '';

        };

        return result;
        }
      }

    try {
        AwsRds.setParams(JSON.parse(value));

        return JSON.stringify(AwsRds.getEvents());
      }
    catch (error) {
        error += (String(error).endsWith('.')) ? '' : '.';
        Zabbix.log(3, '[ AWS RDS ] ERROR: ' + error);

        return JSON.stringify({ 'error': error });
    }