<![CDATA[
/*
    $Revision$
    $Id$

    File:       gen_import.wsf
    Calling:    cscript ..\..\..\utils\gen_import\gen_import.wsf UWVA 462 >>genimport.log 2>>&1
    Parameters: 0: customerId
                1: fac_import_app_key
                2: (optioneel) fac_import_refkey met eigen key naar wens
    Context:    Scheduled task
    Note:       LET OP: We includen code van ../../appl/imp/imp_inlezen.js
                        die ook vanuit ASP wordt gebruikt
 */
 ]]>

 <job id="IncludeGenImport">
    <script language="JScript" src="../wsf_shared.js"/>
    <script language="JScript" src="../../appl/imp/imp_shared.js"/>
    <script language="JScript">

    __Log('$Workfile: gen_import.wsf $','$Revision$');
    // De echte gen_import code
    var udl = "../Oracle.udl";
    var Oracle = new ActiveXObject("ADODB.Connection");
    Oracle.Open('File Name='+udl);
    var sql = "BEGIN DBMS_APPLICATION_INFO.SET_MODULE ('gen_import.wsf', NULL); END;";
    Oracle.Execute(sql);
    sql = "BEGIN fac.initsession(NULL); END;"
    Oracle.Execute(sql)

    if (WScript.Arguments.length < 2)
    {
        __Log("Usage: CScript gen_import.wsf XXXX 41 \n"
            +"                           (fac_import_app_key, preferred method)\n"
            +"   or: CScript gen_import.wsf XXXX PERSON\n"
            +"                           (fac_import_app_code, prefix always XXXX)\n");
        WScript.Quit(1);
    }
    var customerId = WScript.Arguments(0);
    var import_app_key = WScript.Arguments(1);
    var ref_key = null;
    if (WScript.Arguments.length > 2)
    {
        ref_key = parseInt(WScript.Arguments(2), 10) || null;
    }
    if (isNaN(parseInt(import_app_key)))
    {
        /* precedence: CUST+appcode, then FAC+appcode, else error */
        var sql = "SELECT i.fac_import_app_key "
                + "  FROM fac_import_app i"
                + " WHERE i.fac_import_app_code = " + safe.quoted_sql(import_app_key)
                + "   AND fac_import_app_prefix = " + safe.quoted_sql(customerId);
        var oRs = Oracle.Execute(sql);
        if (oRs.Eof)
        {
            var sql = "SELECT i.fac_import_app_key "
                    + "  FROM fac_import_app i"
                    + " WHERE i.fac_import_app_code = " + safe.quoted_sql(import_app_key)
                    + "   AND fac_import_app_prefix IS NULL";
            var oRs = Oracle.Execute(sql);
            if (oRs.Eof)
            {
                __Log("Unable to find " + safe.quoted_sql(import_app_key) + " in fac_import_app");
                WScript.Quit(1);
            }
            else
            {
                import_app_key = oRs("fac_import_app_key").Value;
                __Log("Next time change call to: CScript gen_import.wsf "+customerId+" "+import_app_key);
            }
        }
        else
        {
            import_app_key = oRs("fac_import_app_key").Value;
            __Log("Next time change call to: CScript gen_import.wsf "+customerId+" "+import_app_key);
        }
        oRs.Close();
    }

    function ScriptPath()
    {
       return WScript.ScriptFullName.substr(0,
                     WScript.ScriptFullName.length - WScript.ScriptName.length);
    }

    var sql = "SELECT i.fac_import_app_code "
            + ",      i.fac_import_app_prefix "
            + ",      i.fac_import_app_charset "
            + ",      i.fac_import_app_folder "
            + ",      i.fac_import_app_files "
            + "  FROM fac_import_app i"
            + " WHERE i.fac_import_app_key = " + import_app_key;
    var oRs = Oracle.Execute(sql);

    var import_app = oRs("fac_import_app_code").value;

    __Log("Import " + import_app);

    var charset = oRs("fac_import_app_charset").value||'Windows-1252';
    var scanDir = oRs("fac_import_app_folder").Value; // D:\Apps\FacilitorWebdav\export\KCI_SPOBILO\
    var filenames = oRs("fac_import_app_files").Value; // KCI_SPOBILO_W_*.dat
    if (!scanDir)
    {
        __Log("ERROR: fac_import_app_folder is not set");
        WScript.Quit(1);
    }
    if (!filenames)
    {
        __Log("ERROR: fac_import_app_files is not set");
        WScript.Quit(1);
    }
    scanDir = scanDir.replace("/", "\\");
    if (scanDir.substr(scanDir.length-1) != "\\")
        scanDir += "\\";
    __Log("Scanning " + scanDir);

    fso = new ActiveXObject("Scripting.FileSystemObject");

    var reg_files = new RegExp("^" + filenames.toUpperCase().replace(".", "\\.").replace("*", ".*").replace("?", ".") + "$", "i");

    __Log("Scanning for: " + filenames);

    var startFolder = fso.GetFolder(scanDir)
    var fc1 = new Enumerator(startFolder.Files);
    var import_key = -1; // weten we nog niet
    for (; !fc1.atEnd(); fc1.moveNext())
    {
        var fil = fc1.item();
        var filename = fil.Name.toUpperCase();
        if (filename.match(reg_files))
        {
            __Log("Reading: " + scanDir + filename);
            var fileStream = new ActiveXObject("ADODB.Stream");
            fileStream.CharSet = charset; // Vroeg, anders krijgen we een BOM?
            fileStream.Open();
            fileStream.LoadFromFile(scanDir + filename);

            try
            {
                var importres = impReadStream(fileStream, import_app_key,
                                                { import_key: import_key,
                                                  ref_key: ref_key,
                                                  fac_home: ScriptPath().toLowerCase().replace("utils\\gen_import\\",""),
                                                  filepathname: filename,
                                                  customerId: customerId});
            }
            catch (e)
            {
                importres = { success: false, import_key: "FAIL_"+toDateTimeString(new Date).replace(/\:/g,"_"), warning: "Error in calling impReadStream\n" + e.description };
            }
            import_key = importres.import_key;

            // impReadStream heeft backDir bepaald voor ons
            // deze file backuppen
            if (importres.backDir)
                fso.MoveFile(scanDir + filename, importres.backDir + filename);

            if (!importres.success)
            {
                __Log(importres.warning);
                WScript.Quit(1); // Hopelijk is de file al wel weg
            }
        }
    }
    if (import_key == -1)
    {
        __Log("No files");
        WScript.Quit(0);
    }

    // Alle bestanden zijn nu ingelezen, waarbij de ongeldigen zijn overgeslagen
    // Nu het echte verwerken
    var processres = impProcessStream(import_key, { customerId: customerId });

    // Tenslotte de logging ook naar een .log file
    var logfile = importres.backDir + "RUN_" + import_key + ".log";
    __Log('Writing logfile ' + logfile);
    sql = " SELECT TO_CHAR(IMP_LOG_DATUM,'YYYY-MM-DD HH24:MI:SS')||';'||IMP_LOG_STATUS||';'||IMP_LOG_OMSCHRIJVING||';'||IMP_LOG_HINT"
        + "   FROM IMP_LOG "
        + "  WHERE FAC_IMPORT_KEY = " + import_key
        + "  ORDER BY IMP_LOG_KEY";
    var oRs = Oracle.Execute(sql)
    if (!oRs.EOF) // Voorkom lege file
    {
        var logStream = new ActiveXObject("ADODB.Stream");
        var fhandle = fso.OpenTextFile(logfile, 2, true); // forWriting, create
        while (!oRs.EOF)
        {
          fhandle.WriteLine(oRs(0).Value);
          oRs.MoveNext();
        }
        fhandle.Close();
    }
    oRs.Close();
   </script>
</job>
