<![CDATA[
/*
    $Id$

    File:       api_import_maas.wsf
    Calling:    cscript ..\..\..\APPL\IMP\Maas\api_import_maas.wsf
                vanuit \\CUST\<custid>\import
    Parameters: 0   loglevel
    Context:    Generiek bestand om een MAAS import te doen.

    Note:       - In de cust/xxxx folder moet een map "Maas" aanwezig zijn die het te
                  importeren xml-bestand bevat.
*/
]]>

<job id="IncludeGenExport">
  <script language="JScript" src="../../../UTILS/PutOrders/json2.js"/>

  <script language="JScript">
    // parameters
    if (WScript.Arguments.length > 0)
        loglevel = WScript.Arguments(0);

    var applicatieRun = new Date();
    WScript.Echo("===========================================================");
    WScript.Echo("API_IMPORT_MAAS started  (" + date2string(applicatieRun) + ")");

    var leverancierConfig = getLeverancierParams();

    try
    {
        fso = new ActiveXObject("Scripting.FileSystemObject");
        objRS = new ActiveXObject("ADODB.Recordset");
        objRS.CursorLocation = 3;               // useClient
        objRS.Fields.Append ("Name", 200, 100); // adVarChar
        objRS.Fields.Append ("created", 7 );    // adDate
        objRS.Open();

        try
        {
            var backdir_api = ".\\BACKUP"+(new Date).getFullYear()+"\\";
            if (!fso.FolderExists(backdir_api))
                fso.CreateFolder(backdir_api);
            backdir_api += leverancierConfig.api + "\\";
            if (!fso.FolderExists(backdir_api))
                fso.CreateFolder(backdir_api);
        }
        catch (e)
        {
            WScript.Echo("Cannot create backup folder " + backDir + "\n" + e.description);
            WScript.Quit();
        }

        // plaats de bestandsnamen en creatiedata in een resultset om deze vervolgens te kunnen filteren.
        folder = leverancierConfig.folder.replace(/\//g,"\\");
        WScript.Echo("Folder: " + folder);
        var f = fso.GetFolder(folder);
        var fc = new Enumerator(f.files);
        var filecount = 0;
        for (; !fc.atEnd(); fc.moveNext())
        {
            filename = fc.item().name;
            WScript.Echo("File: " + filename);
            var file = fso.GetFile(folder + filename);
            var dt = new Date(file.DateCreated);
            WScript.Echo("File: " + filename  + " timestamp:" + date2string(dt));
            if (fc.item().name.indexOf(".xml") != -1)
            {
                filecount++;
                objRS.AddNew();
                objRS("Name") = filename;
                objRS("created") = file.DateCreated;
            }
        }

        //WScript.Echo("filecount " + filecount);
        if (filecount > 0) {
            objRS.Sort = "created ASC";
            objRS.MoveFirst();
            while (!objRS.EOF)
            {
                filename = objRS("Name").Value;
                //WScript.Echo("File (sorted): " + filename);
                objRS.MoveNext();
                var fileStream = new ActiveXObject("ADODB.Stream");
                fileStream.open();
                fileStream.CharSet = "Windows-1252"; // het doel
                fileStream.LoadFromFile(folder + filename);
                WScript.Echo("Filesize " + fileStream.Size);
                fileStream.Position = 0;
                WScript.Echo("Request1: " + fileStream.ReadText);
                fileStream.Position = 0;
                XMLReq = fileStream.ReadText;
                WScript.Echo("Request: " + XMLReq);
                WScript.Echo("URL: " + leverancierConfig.url);
                var objXMLHTTP = new ActiveXObject("MSXML2.ServerXMLHTTP.6.0");

                objXMLHTTP.open("POST", leverancierConfig.url);

                objXMLHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
                objXMLHTTP.send(XMLReq);

                WScript.Echo("Status: " + objXMLHTTP.status);
                WScript.Echo("StatusText: " + objXMLHTTP.statusText);
                WScript.Echo("Result: " + objXMLHTTP.responseText);

                if (objXMLHTTP.status == 200)
                {
                    jsDate = new Date;
                    dateString = date2string(jsDate, "D");
                    timeString = date2string(jsDate, "T");
                    backDir = backdir_api + dateString + "_" + leverancierConfig.api + "\\";
                    if (!fso.FolderExists(backDir))
                        fso.CreateFolder(backDir)
                    // deze file backuppen
                    //WScript.Echo("from:" + filename);
                    //WScript.Echo("to:" + backDir + timeString + "_" + filename);
                    fso.MoveFile(folder + filename, backDir + timeString + "_" + filename);
                }
            }
        }
    }
    catch (e)
    {
        WScript.Echo("Serieuze fout in MaasStatusResponse.wsf: " + e.description)
        WScript.Quit(1);
    }

    var endDate = new Date();
    var duration = Math.round((endDate - applicatieRun) / 10) / 100;
    WScript.Echo("API_IMPORT_MAAS finished ({0}, duration {1}s)".format(date2string(endDate), duration));
    WScript.Quit(0);

// FUNCTIES

    function getLeverancierParams()
    {
        var fso  = new ActiveXObject("Scripting.FileSystemObject");
        // We zijn altijd gescheduled vanuit cust/XXXX
        f = fso.OpenTextFile("./api_import_maas.config", 1);
        c = {};
        try
        {
            c = JSON.parse(f.ReadAll());
            c.url = c.cust_url
                  + "/default.asp"
                  + "?API=" + c.api
                  + "&APIKEY=" + c.apikey;
            c.success = true;
        }
        catch(e)
        {
            c.success = false;
        }
        return c;
    }

    function date2string(mydate, dateOrTime)
    {
        function padout(number)
        {
            return (number < 10) ? "0" + number : number;
        }

        var dateString = padout(mydate.getFullYear())    + "-"
                       + padout(mydate.getMonth() + 1)   + "-"
                       + padout(mydate.getDate());
        var timeString = padout(mydate.getHours())       + "-"
                       + padout(mydate.getMinutes() + 1) + "-"
                       + padout(mydate.getSeconds());
        var dateOrTime = dateOrTime || "";
        var result = "";
        if (dateOrTime.toUpperCase() == "D")
            result = dateString;
        else if (dateOrTime.toUpperCase() == "T")
            result = timeString;
        else
            result = dateString + " " + timeString;

        return result;
    }

  </script>
</job>