/*
    $Revision$
    $Id$

    File:           ExchangeAll.js

    Description:    Exchange EWS koppeling
                    Maakt vanuit database een tmp_Exchange_all.bat in de huidige
                    folder met voor elke ruimte met extern_id een regel

    Parameters:     (net als gen_import.wsf)
                    0: customerId
                    1: fac_import_app_key/code voor de EXCHANGE import of de EXCHFULL import
                    2: fac_import_app_key/code voor de EXCHSYNC import
*/

var fso = new ActiveXObject("Scripting.FileSystemObject");
if (WScript.Arguments.length < 3)
{
    __Log("Usage: CScript ExchangeAll.js CUST EXCHANGE EXCHSYNC");
    WScript.Quit(1);
}
var customerId = WScript.Arguments(0);
var import_app_key = WScript.Arguments(1);
var sync_app_key = WScript.Arguments(2);

var batfile = "./tmp_Exchange_all.bat";

function __Log(s)
{
    var flog = fso.OpenTextFile("ExchangeAll.js.log", 8 /* ForAppending */, true /* create */);
    flog.WriteLine(s);
    flog.Close();
}

__Log("Starting rev. $Revision$ at " + new Date());

var udl = "../Oracle.udl";
var Oracle = new ActiveXObject("ADODB.Connection");
Oracle.Open('File Name='+udl);

var sql = "SELECT res_ruimte_key,"
        + "       res_ruimte_extern_id"
        + "  FROM res_ruimte"
        + " WHERE res_ruimte_verwijder IS NULL"
        + "   AND res_ruimte_extern_id IS NOT NULL";

var oRs = Oracle.Execute(sql);


function pad(n) { return n < 10 ? '0' + n : n };
var dt = new Date();
var logfile = "Exchange_" + dt.getUTCFullYear() + '_' + pad(dt.getUTCMonth() + 1) + "_" + import_app_key + ".log";


var fbat = fso.CreateTextFile(batfile, true /* overwrite */);
while (!oRs.Eof)
{
    var line = 'CScript /NoLogo ..\\..\\..\\utils\\Exchange\\Exchange.js "'
                    + oRs("res_ruimte_extern_id").Value + '" "' + import_app_key + '"'
                    + ' >>' + logfile + ' 2>>&1';
    fbat.WriteLine(line);
    if (import_app_key != "EXCHFULL") // De full calender heeft geen syncstate in zich
    {
        var line = 'IF NOT ERRORLEVEL 1 Cscript /NoLogo ..\\..\\..\\utils\\gen_import\\gen_import.wsf '
                        + customerId + ' ' + sync_app_key + ' ' + oRs("res_ruimte_key").Value + ' >>' + logfile + ' 2>>&1';
        fbat.WriteLine(line + "\n");
    }
    oRs.MoveNext();
}

// Eén import aan het eind; de room-id is toch uit de XML te halen
fbat.WriteLine("REM Alles is nu ingelezen. Tijd om te gaan verwerken");
var line = 'Cscript /NoLogo ..\\..\\..\\utils\\gen_import\\gen_import.wsf '
              + customerId + ' ' + import_app_key + ' >>' + logfile + ' 2>>&1';
fbat.WriteLine(line);

fbat.Close();
oRs.Close();

__Log("Done at " + new Date());
