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

    File:       gen_export.wsf
    Calling:    cscript ..\..\..\utils\gen_export\gen_export.wsf 234 >>genexport.log 2>>&1
    Parameters: fac_export_app_key of fac_import_app_code
    Context:    Scheduled task
    Note:
 */
 ]]>

<job id="IncludeGenExport">
  <script language="JScript" src="../wsf_shared.js"/>
  <script language="JScript" src="../utils_settings.js"/>
  <script language="JScript" src="../../appl/exp/exp_shared.js"/>
  <script language="JScript">

    if (isOffline())
    {
        __Log("FACILITOR is offline, export skipped");
        WScript.Quit(1);
    }

    __Log('$Id$');

    var fso  = new ActiveXObject("Scripting.FileSystemObject");
    // We zijn altijd gescheduled vanuit cust/XXXX/gen_export
/* global */ var custabspath = fso.GetAbsolutePathName("../");

     var WshNetwork = new ActiveXObject("WScript.Network");
    __Log("User: " + WshNetwork.UserDomain + "\\" + WshNetwork.UserName);

    if (WScript.Arguments.length < 1)
    {
      __Log("Usage: CScript gen_export.wsf [fac_export_app_key | fac_import_app_code] but better use gen_export.bat");
      WScript.Quit();
    }

    var export_app_id = WScript.Arguments(0);

    var Oracle = Connect2Oracle('gen_export.wsf ' + export_app_id);

    var sql = "SELECT fac_version_cust FROM fac_version";
    var oRs = Oracle.Execute(sql);
    var customerId = oRs(0).Value;
    oRs.Close();

    app_key = getAppKey(export_app_id);
    if (app_key == -1)
      WScript.Quit();

    var ini = getSettings(app_key);
    ini.tempFolder = '../../temp';

    ini.applrun = new Date;
    ini.custid = customerId.toUpperCase();
    ini.fac_home = ScriptPath().toLowerCase().replace("utils\\gen_export\\",""),
    ini.customerId = customerId;

    if (!taskScheduled(ini))
        WScript.Quit(); // snel klaar
    try
    {
      var streamParams = {streamwrite: 2};
      var toMulti = ini.fileprefix.charAt(0) == "*";

      if (toMulti)
      {
        var filename;
        var fstr;
        var expPath;
        var exportFile;
        preExport(ini);
        var streamData = exportToStream(ini, exportFile);
        for (var i = 0; i < streamData.length; i++)
        {
          filename = String(streamData[i].filename);
          fstr = streamData[i].fstr;

          exportFile = getFileName(filename, ini.postfix, ini.applrun, ini.timestamp);
          expPath = checkDestination(ini.folder, exportFile, streamParams);
          if (expPath.success)
          {
            if (fstr)
            {
              __Log("Writing: " + expPath.destination + " (" + fstr.Size + " bytes)");

              fstr.SaveToFile(expPath.destination, streamParams.streamwrite);
              fstr.Close();
            }
          }
          else
          {
            __Log(expPath.message);
          }
          // Nu de logfile schrijven
          writeLog(ini, filename, streamParams);
        }
        postExport(ini);
      }
      else
      {
        var exportFile = getFileName(ini.fileprefix, ini.postfix, ini.applrun, ini.timestamp);
        var expPath = checkDestination(ini.folder, exportFile, streamParams);
        if (expPath.success)
        {
          preExport(ini);
          var streamData = exportToStream(ini, exportFile);
          if (streamData)
          {
            if (ini.compress)
                expPath.destination += '.zip';
            __Log("Writing: " + expPath.destination + " (" + streamData.Size + " bytes)");

            streamData.SaveToFile(expPath.destination, streamParams.streamwrite);
            streamData.Close();
          }
          postExport(ini);
        }
        else
        {
          __Log(expPath.message);
        }
        // Nu de logfile schrijven
        writeLog(ini, ini.fileprefix, streamParams);
      }
      // Datum in imp_schedule zetten
      scheduledDone(ini);
    }
    catch (e)
    {
        var txt = "Scheduled export {0} error: {1}".format(export_app_id, e.description);
        __Log(txt, { severity: "E" });
        var sql = "BEGIN fac.putsystemnotification({0}, 3); END;".format(safe.quoted_sql(txt)); // 3=portal+email
        Oracle.Execute(sql); // hopen dat dit wel lukt
    }
    __Log("End gen_export.wsf");

//
// FUNCTIES
//

    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 getAppKey(app_id)
    {
      // Get a valid fac_export_app_key by app_code or app_key
      //
      var export_app_key = -1;
      if (isNaN(parseInt(app_id)))
      {
        var sql = "SELECT fac_export_app_key"
                + "  FROM fac_export_app"
                + " WHERE fac_export_app_code = " + safe.quoted_sql(app_id.toUpperCase());
        var oRs = Oracle.Execute(sql);
        if (oRs.Eof)
        {
            __Log("Unable to find " + safe.quoted_sql(app_id) + " in fac_export_app");
        }
        else
        {
            export_app_key = oRs("fac_export_app_key").Value;
        }
        oRs.Close();
      }
      else
      {
        var sql = "SELECT fac_export_app_key"
                + "  FROM fac_export_app"
                + " WHERE fac_export_app_key = " + app_id;
        var oRs = Oracle.Execute(sql);
        if (oRs.Eof)
        {
            __Log("Unable to find " + app_id + " in fac_export_app");
        }
        else
        {
            export_app_key = app_id;
        }
        oRs.Close();
      }
      return export_app_key;
    }

    function logErrors(folderfile, ini, params)
    {
        // log errors
        var params = params || {};
        var streamwrite = (params.streamwrite ? params.streamwrite : 1);
        if (ini.logpostfix != "")
        {
            var sql = "SELECT imp_log_datum||';'||imp_log_status||';'||imp_log_omschrijving||';'||imp_log_hint result"
                    + "  FROM imp_log"
                    + " WHERE imp_log_applicatie = " + safe.quoted_sql(ini.code)
                    + " ORDER BY imp_log_datum";
            var oRs = Oracle.Execute(sql);
            if (!oRs.Eof)
            {
                fstr = openStreamWriteText({charset: ini.charset});
                while (!oRs.Eof)
                {
                   fstr.WriteText(oRs("result").Value, 1); // 0=adWriteChar, 1=adWriteLine (LineSeparator required);
                   oRs.MoveNext();
                }
                fstr.Position = 0;
                fstr.SaveToFile(folderfile, streamwrite);
                fstr.Close();
            }
        }
    }

    function writeLog(ini, fileprefix, streamParams)
    {
        var logFile = getFileName(fileprefix, ini.logpostfix, ini.applrun, ini.timestamp);
        var logPath = checkDestination(ini.folder, logFile, streamParams);
        if (logPath.success)
        {
          logErrors(logPath.destination, ini, {streamwrite: 2});
        }
        else
        {
          __Log(logPath.message);
        }
    }

    function checkDestination(folder, file, params)
    {
        // params
        //   streamwrite:   1=adSaveCreateNotExist, 2=adSaveCreateOverWrite
        var param = params || {};
        var result = {destination: "", message: "", success: false};
        var folderfile = folder + "\\" + file;
        var streamwrite = (params.streamwrite ? params.streamwrite : 1);

        var fso = new ActiveXObject("Scripting.FileSystemObject");
        if (!fso.FolderExists(folder))
        {
            result.message = "Folder " + folder + " does not exist.";
        }
        else
        {
            if (fso.fileExists(folderfile) && streamwrite == 1)
            {
                // Bestand bestaat al, dus kan niet nogmaals gemaakt worden.
                result.message = "File " + folderfile + " already exists.";
            }
            else
            {
                result.destination = folderfile;
                result.success = true;
            }
        }
        return result;
    }

    function taskScheduled(params)
    {
      // Look if there is a task in the table IMP_SCHEDULE if Manual = 1
      var result = true;

      if (params.manual)
      {
        var sql = "SELECT imp_schedule_key, prs_perslid_key FROM imp_schedule"
                + " WHERE imp_schedule_done IS NULL"
                + "   AND imp_schedule_name = " + safe.quoted_sql(params.code);
        __Log("SQL: " + sql);
        var oRs = Oracle.Execute(sql);
        if (oRs.eof)
        {
          __Log("Not scheduled. Skipping.");
          result = false;
        }
        else if (oRs("prs_perslid_key").Value)
        {
            // Export procedure kan deze met sys_context('USERENV', 'CLIENT_IDENTIFIER'); uitlezen als hij dat wil
            var sql = "BEGIN DBMS_SESSION.SET_IDENTIFIER(" + oRs("prs_perslid_key").Value + "); END;";
            Oracle.Execute(sql);
        }
        oRs.Close();
      }

      return result;
    }
    Oracle.Close();

    function scheduledDone(params)
    {
      if (params.manual)
      {
        var sql = "UPDATE imp_schedule"
                + "   SET imp_schedule_done = SYSDATE"
                + " WHERE imp_schedule_done IS NULL"
                + "   AND imp_schedule_name = " + safe.quoted_sql(params.code);
        __Log("SQL: " + sql);
        Oracle.Execute(sql);
      }
    }

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

  </script>
</job>
