// ******************************************
// * $Id$
// *
// *   Log2File()
// *   cleanPopup()
// *
// * Base64 encode / decode
// * http://www.webtoolkit.info/
// *
// ******************************************

var logfso = new ActiveXObject("Scripting.FileSystemObject");
function Log2File(level, str, fatal)
{
    // uses:  scr="../wsf_shared.js"
    //        src="./puo_settings.js"
    //
    var dtstr = toDateTimeString(new Date);
    if (level <= 1 && (typeof WScript != 'undefined'))
    {
        if (typeof WScript != 'undefined')
            WScript.Echo(dtstr + " " + str);
        else if (typeof Response != 'undefined')
        {
            Response.Write("<pre>" + dtstr + " " + safe.html(str) + "</pre>");
            Response.Flush;
        }
    }
    if( level <= S("puo_loglevel"))
    {
        if (S("puo_logdestination")== 1 || S("puo_logdestination")==3)
        {   // Aparte logfile per maand
            var logfilename = customerId + "_" + padout((new Date).getFullYear())  + "_" + padout((new Date).getMonth() + 1) + ".log";
            if (typeof PUO_LOGPATH == "undefined")
                logfilename = "putorders_" + logfilename; // voorkennis: de scheduled versie
            else
                logfilename = PUO_LOGPATH + "putordersI_" + logfilename; // voorkennis: de immediate versie
            try
            {
                var flog = logfso.OpenTextFile(logfilename, 8 /* ForAppending */, true /* create */);
                flog.WriteLine(str);
            }
            catch(e)
            {
                try
                {
                    flog.WriteLine("@@@Could not write str to logfile: " + e.description + "\nIs it perhaps unicode?");
                }
                catch (e)
                {
                    // Waarschijnlijk readonly of anderszins locked
                }
            }
            if (flog)
                flog.Close();
        }
        if (S("puo_logdestination")== 2 || S("puo_logdestination")==3 || fatal)
        {
            var dblevel = "";
            if (level==0) dblevel = "E";
            if (level==1) dblevel = "I";
            if (level==2) dblevel = "D";
            if (fatal)    dblevel = "F";
            // Merk op: de trigger van imp_log zal voor fatal meldingen een notificatie naar
            //          WEB_PRSSYS leden sturen. Een eventuele e-mail wordt de *volgende* run
            //          van putorders pas verstuurd.
            var sql = "INSERT INTO imp_log"
                    + "( imp_log_applicatie"
                    + ", imp_log_datum"
                    + ", imp_log_status"
                    + ", imp_log_omschrijving"
                    + ", imp_log_hint"
                    + ") VALUES"
                    + "( '$PutOrders$'"
                    + ", SYSDATE"
                    + ", " + safe.quoted_sql(dblevel)
                    + ", " + safe.quoted_sql(dtstr + " " + str.substr(0, 990))
                    + ", ''"
                    + ")";
           Oracle.Execute(sql);
        }
    }
}

var logcounter = 0;
function LogString2File(level, postfix, data, ext, isStream)
{
    if(level > S("puo_loglevel"))
        return;

    if (logcounter > 99)
    {
        Log2File(level, "Meer dan 100 logfiles in één run? Ik stop er mee");
        return;
    }
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var folder = custabspath + "/../../temp/" + customerId + "_files";
    if (!fso.FolderExists(folder))
        fso.CreateFolder(folder);
    var jsDate = new Date();
    var s = String(jsDate.getFullYear()) + padout(jsDate.getMonth() + 1) + padout(jsDate.getDate()) + "-"
          + padout(jsDate.getHours()) + padout(jsDate.getMinutes()) + padout(jsDate.getSeconds())
    var log_file = "puo_" + s + "_" + padout(logcounter++);
    log_file = log_file + "_" + postfix + "." + (ext || "txt");

    try
    {
        if (isStream)
        {
            data.SaveToFile(folder + "/" + log_file);
        }
        else
        {
            var ts  = fso.CreateTextFile(folder + "/" + log_file, true);
            ts.WriteLine (data);
            ts.Close();
        }
        Log2File(level, "{0} written to {1} ({2} bytes)".format(postfix, log_file, isStream?data.Size:String(data).length));
    }
    catch (e)
    {
        Log2File(level, "ERROR writing {0} to {1}: {2}".format(postfix, log_file, e.description));
    }
}
function LogStream2File(level, postfix, stream, ext)
{
    LogString2File(level, postfix, stream, ext, true);
}

function cleanPopup()
{
    // Wissen oude (gisteren) popups
    // Met 4.80 wilden we dit eigenlijk via een FAC_JOB en package doen
    Log2File(1, "** START cleanPopup (" + toDateTimeString(new Date) + ")");
    var sql = "UPDATE fac_notificatie n"
            + "   SET n.fac_notificatie_status = BITAND(n.fac_notificatie_status, 255 - 8)"
            + " WHERE BITAND (n.fac_notificatie_status, 8) = 8"
            + "   AND TRUNC (n.fac_notificatie_datum) < TRUNC (SYSDATE)"
    Log2File(3, sql);
    Oracle.Execute(sql);
}


function LogResult(p_path, p_data)
{
    // Schrijf de data naar een bestand. Handig bij testen wat de (tussen)resultaten zijn.
    //
    // p_path: relatief pad met bestandsnaam
    // p_data: tekst string
    //var fsoForReading = 1;
    var fsoForWriting = 2;
    var fso = new ActiveXObject("Scripting.FileSystemObject");

    var pathName = fso.GetAbsolutePathName(p_path);
    var fileName = fso.GetFileName(pathName);
    __Log("writing " + p_data.length + " bytes of data to: " + fileName);
    var folderName = fso.GetParentFolderName(pathName);
    if (fso.FolderExists(folderName))
    {
        var fpt = fso.OpenTextFile(pathName, fsoForWriting, true);
        fpt.Write(p_data);
        fpt.Close();
    }
}

function stream2text(stream)
{
    stream.Position = 0;
    var txt = stream.ReadText();
    stream.Position = 0;
    return txt;
}

function trimall(s)
{
    //Spaties *en quotes* er af
    s = s.replace(/^\s+|\s+$/g,"");
    s = s.replace(/^\'+|\'+$/g,"");
    s = s.replace(/^\"+|\"+$/g,"");
    return s;
}

function doHTTP(url, params) // params is sterk vergelijkbaar met p_bedrijfadres
{
    params = params || {};
    if (!params.method)
        params.method = params.data?"POST":"GET"; // Met data default POST, zonder data default GET
    if (!params.headers)
        params.headers = {};

    var http_request = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
    // contanten in msxml2
    var SXH_PROXY_SET_PROXY = 2;
    var SXH_OPTION_SELECT_CLIENT_SSL_CERT = 3;
    if (S("puo_useproxy"))
    {
        var proxy_ip = S("puo_proxyserveripaddress");
        Log2File(2, "Opening proxy " + proxy_ip);
        http_request.setProxy(SXH_PROXY_SET_PROXY, proxy_ip);
    }

    if (params.certificateName)
    {
        Log2File(1, "Client certificateName= " + params.certificateName);
        http_request.setOption(SXH_OPTION_SELECT_CLIENT_SSL_CERT, params.certificateName);
    }

    if (params.username && params.authmethod == 1) // Forced base64
    {
      var base64 = new Base64Cls();
      params.headers["Authorization"] = "Basic " + base64.encode(params.username + ":" + params.password);
    }
    if (params.username && params.authmethod == 2) // Custom header, bijvoorbeeld user=X-FACILITOR-API-Key, pass=VERYSECRET
    {
      params.headers[params.username] = params.password;
      params.username = null;
      params.password = null;
    }
    if (params.username && params.authmethod == 3) // Stonden ze (al) in de XML
    {
      params.username = null;
      params.password = null;
    }
    http_request.open(params.method, url, false, params.username, params.password); // Synchroon

    for (var head in params.headers)
        http_request.setRequestHeader(head, params.headers[head]);

    // let op: params.data kan een string of ADODB.Stream zijn. Daarom moet de aanroeper maar loggen
    http_request.send(params.data);
    if (http_request.status < 200 || http_request.status > 299)
    {
        var ext = null;
        var ctype = String(http_request.getResponseHeader("Content-Type"));
        if (ctype.indexOf("xml") > 0)
            ext = "xml"
        else if (ctype.indexOf("html") > 0)
            ext = "html";
        else if (ctype.indexOf("json") > 0)
            ext = "json";
        Log2File(1, "response Status = " + http_request.status + ": " + http_request.statusText);
        LogString2File(2, "HTTP response", http_request.responseText, ext); // Level 2 omdat het soms dagen doorloopt en te groot is
        Log2File(3, "response Headers = " + http_request.getAllResponseHeaders);
        RaiseAnError(http_request.status, "http_request error " + http_request.status + ": (" + http_request.statusText + ")");
    }
    else
    {
        Log2File(3, "response = " + http_request.responseText);
    }
    return http_request;
}