/*
    $Id$
 */

var unit4 =
{
    unit4url : null,
    refresh_token : null,

    freshToken : null,
    scope : "http://UNIT4.Multivers.API/Web/WebApi/*",

    init: function (params)
    {
        unit4.unit4url = params.unit4url;
        unit4.refresh_token = params.refresh_token;
        unit4.freshToken = unit4.getToken(); // Doorgaans 2 uur geldig, genoeg voor deze run
    },

    getToken: function()
    {
        var body = ["grant_type=refresh_token",
                    "refresh_token=" + unit4.refresh_token,
                    "client_id=dummy",
                    "client_secret=dummy"
                   ].join("&");
        var jresp = unit4.apiUnit4("POST", "/OAuth/Token/", body);
        return jresp.access_token;
    },

    // Altijd json terug
    apiUnit4: function (method, url, body)
    {
        var xmlhttp = new ActiveXObject("WinHTTP.WinHTTPRequest.5.1");
        SXH_PROXY_SET_PROXY = 2;
        if (config.proxy)
            xmlhttp.setProxy(SXH_PROXY_SET_PROXY, config.proxy);

        var WinHttpRequestOption_SslErrorIgnoreFlags = 4;
        xmlhttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = 0x3300; // Ignore all

        xmlhttp.open(method, unit4.unit4url + url, false); // false dus sync

        xmlhttp.setRequestHeader("Accept", "application/json"); // Dat willen wij altijd terug
        if (body)
        {
            if (typeof body == 'object')
            {
                xmlhttp.setRequestHeader("Content-Type", "application/json");
                body = JSON.stringify(body);
            }
            else
            {
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        }

        if (unit4.freshToken)
            xmlhttp.setRequestHeader("Authorization", "Bearer " + unit4.freshToken);
        xmlhttp.send(body);

        if (xmlhttp.status == 404)
        {
            return null;
        }
        if (xmlhttp.status == 200)
        {
            try
            {
                var txt = xmlhttp.responseText || "{}";
                var result_data = eval("(" + txt + ")");
                return result_data;
            }
            catch (e)
            {
                // Waarschijnlijk http-error terug gekregen
                __Log(method + " " + unit4.unit4url + url + "\nBody:\n" + body);
                __Log("eval failed: " + e.description);
                __Log(txt);
                return { error: true };
            }
        }
        else
        {
            __Log(method + " " + unit4.unit4url + url + "\nBody:\n" + body);
            __Log("Status: " + xmlhttp.status + " " + xmlhttp.statusText);
            __Log(xmlhttp.responseText);
            return { error: true };
        }
    }
}