var params = JSON.parse(value);

var request = new HttpRequest();

request.addHeader('Content-Type: application/json');
request.addHeader('Authorization: Token ' + params.token);

var response,
    output,
    error_msg = '',
    enterprises = [],
    edges = [],
    links = [],
    gateways = [],
    version = [],
    apps = [],
    appsLinks = [],
    edgeSDWan = [],
    edgeSDWanPath = [];

function getHttpData(url, body) {
    response = request.post(url, body);
    Zabbix.log(4, '[ SD-WAN API ] [ ' + url + ' ] Received response with status code ' + request.getStatus() + ': ' + response);

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

    if (request.getStatus() !== 200) {
        if (response.error && response.error.message) {
            throw response.error.message;
        } else {
            throw 'Failed to receive data: invalid response status code.';
        }
    }

    if (typeof (response) !== 'object' || response === null) {
        throw 'Cannot process response data: received data is not an object.';
    }

    return response;
};

try {

    if (params.token === '{' + '$VELOCLOUD.TOKEN}') {
        throw 'Please change {' + '$VELOCLOUD.TOKEN} macro with the proper value.';
    }

    if (params.url.indexOf('http://') === -1 && params.url.indexOf('https://') === -1) {
        params.url = 'https://' + params.url;
    }

    if (!params.url.endsWith('/')) {
        params.url += '/';
    }

    enterprises = getHttpData(params.url + 'portal/rest/monitoring/getAggregates', '{}').enterprises;

    if (!Array.isArray(enterprises)) {
        throw 'Cannot process edges: enterprises is not an array.';
    }

    links = getHttpData(params.url + 'portal/rest/monitoring/getAggregateEdgeLinkMetrics', '{}');
    gateways = getHttpData(params.url + 'portal/rest/network/getNetworkGateways', JSON.stringify({ with: ['site'] }));
    version = getHttpData(params.url + 'portal/rest/system/getVersionInfo', '{}');

    for (var i in enterprises) {
        responseEdges = getHttpData(params.url + 'portal/rest/enterprise/getEnterpriseEdges', JSON.stringify({ enterpriseId: enterprises[i].id, with: ['site'] }));
        edges = edges.concat(responseEdges);
    }

    if (!Array.isArray(edges)) {
        throw 'Cannot process edges SDWans: edges is not an array.';
    }

    for (var i in edges) {
        responseEdgeSDWan = getHttpData(params.url + 'portal/rest/edge/getEdgeSDWANPeers', JSON.stringify({ enterpriseId: edges[i].enterpriseId, edgeId: edges[i].id }));

        if (!Array.isArray(responseEdgeSDWan)) {
            throw 'Cannot process edges SDWan Path: edges SDWans is not an array.';
        }

        for (var e in responseEdgeSDWan) {
            data = {
                'enterpriseId': edges[i].enterpriseId,
                'edgeId': edges[i].id,
                'peerLogicalId': responseEdgeSDWan[e].deviceLogicalId
            };
            responseEdgeSDWanPath = getHttpData(params.url + 'portal/rest/metrics/getEdgeSDWANPeerPathMetrics', JSON.stringify(data));
            edgeSDWanPath = edgeSDWanPath.concat(responseEdgeSDWanPath);

            responseEdgeSDWan[e].edgeId = edges[i].id;
            responseEdgeSDWan[e].edgeName = edges[i].name;
            responseEdgeSDWan[e].enterpriseId = edges[i].enterpriseId;
        }

        edgeSDWan = edgeSDWan.concat(responseEdgeSDWan);
    }

} catch (error) {
    error_msg = error;
};

return JSON.stringify({
    'enterprises': enterprises,
    'edges': edges,
    'links': links,
    'gateways': gateways,
    'edgeSDWan': edgeSDWan,
    'edgeSDWanPath': edgeSDWanPath,
    'info': version,
    'error': error_msg.toString()
});