// ******************************************
// * $Id$
// *
// *   tasker_loop()
// *
// * Start relevante taken
// *
// * Uses: scr="../wsf_shared.js"
// *       scr="./puo_settings.js"
// *       scr="./puo_shared.js
// *
// ******************************************
var fso = new ActiveXObject("Scripting.FileSystemObject");

function tasker_loop(params)
{
    params = params || {};

    Log2File(2, "** START tasker_loop (" + toDateTimeString(new Date()) + ")");

    var sqltask
            = "SELECT fac_task_key"
            + "     , fac_cust_customerid"
            + "     , fac_task_code"
            + "     , fac_task_nextrun"
            + "  FROM fac_task tt, fac_cust tsko"
            + " WHERE tt.fac_cust_key = tsko.fac_cust_key"
            + "   AND fac_cust_enabled > 0"
            + "   AND fac_task_nextrun <= SYSDATE"
            + "   AND BITAND(fac_task_flags, 1) = 1" // wel enabled
            + " ORDER BY fac_task_nextrun"
            + "        , fac_cust_customerid";
    Log2File(3, sqltask);

    var lastAction = new Date();

    var zelflastdate = null;
    while (true)
    {
        var sql = "UPDATE fac_version"
                + "   SET fac_version_tasker_date = SYSDATE";
        Oracle.Execute(sql);

        var zelfpath = fso.GetAbsolutePathName("../../../utils/gen_scheduler/gen_tasker.js");
        var fsoFile = fso.GetFile(zelfpath);
        var zelfdate = new Date(fsoFile.DateLastModified);
        if (zelflastdate && zelfdate && zelflastdate.getTime() != zelfdate.getTime())
        {
            var txt = "Reloading tasker. Old get_tasker.js was {0}, new one is {1}".format(toDateTimeString(zelflastdate), toDateTimeString(zelfdate));
            WScript.Echo(txt);
            return 11; // hoge errorlevel zodat bij onverwachte CScript errors CUST\FCLT\gen_scheduler\gen_tasker.bat niet op hol slaat
        }
        zelflastdate = zelfdate;
        var oRs = Oracle.Execute(sqltask);
        if (oRs.EOF)
        {
            oRs.Close();
            if (typeof WScript != 'undefined')
            {
                var now = new Date();
                var since = Math.round((now.getTime() - lastAction.getTime()) / 1000);
                var sincetxt = "" + Math.floor(since/3600) + ":" + padout(Math.floor(since/60 % 60)) + ':' + padout(since %60)
                var txt = "Tasker has nothing to do since {0} ({1} ago). Sleeping for a while.".format(toDateTimeString(lastAction), sincetxt);
                WScript.Echo(txt);
            }
            //WScript.Sleep(5000);
            var sql = "BEGIN tsk.waittask(pinterval => 3, ptimeout => 60); END;"; // serverside elke 3 seconde pollen gedurende een minuut
            Oracle.Execute(sql);
            continue; // loopje in
        }
        var task_key = oRs("fac_task_key").value;
        var owner_cust = oRs("fac_cust_customerid").value;
        var task_code = oRs("fac_task_code").value;
        var task_notbefore = new Date(oRs("fac_task_nextrun").value);
        oRs.Close();
        var lockfilename = custabspath + "/../../temp/" + customerId + "/" + owner_cust + "_" + task_code + ".lock";
        //lockfilename = fso.GetAbsolutePathName(lockfilename) //
        if (fso.FileExists(lockfilename)) // Already active?
        {
            try {
                fso.DeleteFile(lockfilename);
            }
            catch (e)
            {
                Log2File(1, "{0} Task seems busy in lockfile {1}\nNot starting task, trying again in 1 minute".format(toDateTimeString(new Date()), lockfilename));
                var sqlu = "UPDATE fac_task"
                         + "   SET fac_task_nextrun = fac_task_nextrun + 1/60/24," // Over 1 minuut weer testen
                         + "        fac_task_flags = fac_task_flags + 2 - bitand(fac_task_flags, 2)" // zet bitje 2 om aan te geven dat we busy zijn
                         + " WHERE fac_task_key = " + task_key;
                Oracle.Execute(sqlu);

                continue;
            }
        }

        var sqlu = "UPDATE fac_task"
                 + "   SET fac_task_nextrun = NULL,"
                 + "       fac_task_lastrun = SYSDATE,"
                 + "       fac_task_flags = fac_task_flags - bitand(fac_task_flags, 2)" // reset busy bitje
                 + " WHERE fac_task_key = " + task_key;
        Oracle.Execute(sqlu);

        var now = new Date();
        var late = Math.round((now.getTime() - task_notbefore.getTime()) / 100) / 10;
        Log2File(1, "== Task " + ("    " + task_key).slice(-5) + "; "
                  + owner_cust + " " + task_code
                  + "; notbefore " + toDateTimeString(task_notbefore)
                  + "; started: " + toDateTimeString(new Date())
				  + (late > 1 ?", after " + late + " seconds)": ", within 1 second)")
                  + (params.userident ? " user: " + params.userident : "")
                 );

        var command = null;
        var startin = null;
        switch (task_code)
        {
            case "PUTORDERS":
                var command = 'CMD /C "..\\..\\..\\utils\\putOrders\\putOrders.bat"'; // Moet met backslashes voor CMD
                var startin = custabspath + "/../" + owner_cust + "/tasks"
                break;
            case "EXCHANGE":
                var command = 'CMD /C "..\\..\\..\\utils\\exchange\\process_webhooks.bat"'; // Moet met backslashes voor CMD
                var startin = custabspath + "/../" + owner_cust + "/Exchange"
                break;
            case "TASKERSTOP": // Disable eerst de de Windows scheduled taak als je geen herstart wilt
                return 0;
                break;
            case "TASKERRELOAD": // Reload this JavaScript
                return 10; // hoge errorlevel zodat bij onverwachte CScript errors CUST\FCLT\gen_scheduler\gen_tasker.bat niet op hol slaat
                break;
            default: ERROR_UNKNOWN_task_code;
        }
        // var tempfile = custabspath + "/../../temp/" + customerId + "/" + owner_cust + "_" + task_code + ".bat";
        // overwogen om een tijdelijke batchfile met CD <<startin>> te maken
        // maar Windows toont een security warning popup als je een nieuwe batchfile op W: gaat draaien

        Log2File(2, "Starting " + command);
        Log2File(2, "      in " + startin);

        if (startin && !fso.FolderExists(startin))
        {
            Log2File(1, "Error: could not find start-in folder " + startin);
        }
        else
        {
            try
            {
                var objShell = WScript.CreateObject("WScript.Shell");
                var olddir = objShell.CurrentDirectory;
                objShell.CurrentDirectory = startin;

                var objResult = objShell.Run(command + ">" + lockfilename, S("puo_loglevel")>1?1:0, false); // 0=no window, async
                objShell.CurrentDirectory = olddir;
            }
            catch(e)
            {
                Log2File(0, "Error starting\n    {0}\nin {1}\n{2}".format(command, startin, e.description));
            }
        }

        lastAction = new Date();
    }
}

