<![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="../../appl/exp/exp_shared.js"/>
  <script language="JScript">

    __Log('$Id$');
    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 udl = "../Oracle.udl";
    var Oracle = new ActiveXObject("ADODB.Connection");
    Oracle.Open('File Name='+udl);

    var sql = "BEGIN DBMS_APPLICATION_INFO.SET_MODULE ('gen_export.wsf', NULL); END;";
    Oracle.Execute(sql);
    sql = "BEGIN fac.initsession(NULL); END;"
    Oracle.Execute(sql)

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

    convertIni();

    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();

    if (taskScheduled(ini))
    {
      //
      var streamParams = {streamwrite: 2};
      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
      //
      var logFile = getFileName(ini.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);
      }
      //
      // Datum in imp_schedule zetten
      //
      scheduledDone(ini);
    }
    __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 convertIni()
    {
      // Als er nog geen instellingen in de database zijn, kopieer dan de instellingen naar de database.
      //

      var sql = "SELECT * FROM fac_export_app";
      var oRs = Oracle.Execute(sql);
      if (!oRs.Eof)
      {
        oRs.Close();
        return; // al klaar
      }

      // Tijdelijke oplossing om de kolom fac_export_app_prefix 60 tekens lang te maken.
      // Met 5.4.2 is deze lange fac_export_app_prefix verschoven naar fac_export_app_file_prefix
      // en is er een nieuwe fac_export_prefix gemaakt waarin de (afwijkende) custid komt te staan.
      // De tabel hoeft dus niet meer aangepast te worden.
      // var sql = "ALTER TABLE fac_export_app MODIFY fac_export_app_prefix VARCHAR2(60)";
      // __Log("SQL: " + sql);
      // Oracle.Execute(sql);
      //
      var sql = "SELECT fac_version_cust FROM fac_version";
      var oRs = Oracle.Execute(sql);
      var CustId = oRs(0).Value;
      oRs.Close();

      var fso = new ActiveXObject("Scripting.FileSystemObject");
      var genini = "gen_export.ini";
      if (fso.FileExists(genini))
      {
        __Log("Converting " + genini);
        var f = fso.OpenTextFile(genini, 1); // 1=ForReading
        var tekst = f.ReadAll();
        f.Close();
        var secties = tekst.split("\n[");
        for (var sectie in secties)
        {
          var lines = secties[sectie].split("\n");
          var sectienaam = trimall(lines[0].replace(/[\[|\]]/ig, "")).toUpperCase();
          if (sectienaam == "ADO" || sectienaam == "SYSTEM")
            continue;
          //
          __Log("sectie: '" + sectienaam + "' " + lines.length + " lines");
          var ExportCharset = "";
          var ExportFolder = "";
          var ExportPrefix = "";
          var ExportPostfix = "";
          var ExportStyleSheet = "";
          var LogPostfix = "";
          var BackupTimestamp = "";
          var Manual = 0;
          var System = "";

          for (var l in lines)
          {
            var sp = lines[l].split("=")
            if (sp.length != 2)
              continue;
            var nm = trimall(sp[0]);
            var vl = trimall(sp[1]);
            switch (nm.toLowerCase())
            {
              case "encoding":
                  ExportCharset = vl;
                  break;
              case "localpath":
                  ExportFolder = vl||".";
                  break;
              case "exportfileprefix":
                  ExportPrefix = vl;
                  break;
              case "exportfilepostfix":
                  ExportPostfix = vl;
                  break;
              case "stylesheet":
                  ExportStyleSheet = vl;
                  if (ExportStyleSheet.substring(0, 3) == "../")
                    ExportStyleSheet = ExportStyleSheet.substring(3); // Haal ../ er af: wij redeneren vanuit cust-folder
                  if (ExportStyleSheet.substring(0, 2) == "./")
                    ExportStyleSheet = "export/" + ExportStyleSheet.substring(2);
                  break;
              case "logfilepostfix":
                  LogPostfix = vl;
                  break;
              case "backupfiletimestamp":
                  BackupTimestamp = vl.replace("hhmm", "HHMM");
                  break;
              case "manual":
                  Manual = ((parseInt(vl) > 0) ? 2 : 0);
                  break;
              case "system":
                  System = ((parseInt(vl) > 0) ? "FAC" : CustId);
                  break;
            }
          }

          if (ExportFolder && ExportPostfix)
          {
            if (ExportFolder == ".")
              ExportFolder = "../export/";
            //
            __Log("Found '" + sectienaam + "' '" + ExportFolder + "' '" + ExportPrefix + "*" + ExportPostfix + "'");
            sql = "SELECT *"
                + "  FROM fac_export_app"
                + " WHERE fac_export_app_code = " + safe.quoted_sql(sectienaam)
                + "   AND fac_export_app_file_prefix IS NOT NULL";
            //__Log(sql);
            var oRs = Oracle.Execute(sql);
            if (!oRs.Eof)
            {
              __Log("Reuse key " + oRs("fac_export_app_key").Value);
              var flags_old = oRs("fac_export_app_flags").Value;
              var Zip = ((flags_old & 1) === 1 ? 1 : 0);
              sql = "UPDATE fac_export_app"
                  + "   SET fac_export_app_charset = "     + safe.quoted_sql(ExportCharset)
                  + "   ,   fac_export_app_folder = "      + safe.quoted_sql(ExportFolder)
                  + "   ,   fac_export_app_prefix = "      + safe.quoted_sql(System)
                  + "   ,   fac_export_app_file_prefix = " + safe.quoted_sql(ExportPrefix)
                  + "   ,   fac_export_app_postfix = "     + safe.quoted_sql(ExportPostfix)
                  + "   ,   fac_export_app_xsl = "         + safe.quoted_sql(ExportStyleSheet)
                  + "   ,   fac_export_app_log_postfix = " + safe.quoted_sql(LogPostfix)
                  + "   ,   fac_export_app_timestamp = "   + safe.quoted_sql(BackupTimestamp)
                  + "   ,   fac_export_app_flags = "       + (Manual | Zip)
                  + " WHERE fac_export_app_key = " + oRs("fac_export_app_key").Value
              //__Log(sql);
              Oracle.Execute(sql);
            }
            else
            {
              __Log("New entry '" + sectienaam + "'");
              sql = "INSERT INTO fac_export_app"
                  + "( fac_export_app_code"
                  + ", fac_export_app_oms"
                  + ", fac_export_app_charset"
                  + ", fac_export_app_folder"
                  + ", fac_export_app_prefix"
                  + ", fac_export_app_file_prefix"
                  + ", fac_export_app_postfix"
                  + ", fac_export_app_xsl"
                  + ", fac_functie_key"
                  + ", fac_export_app_log_postfix"
                  + ", fac_export_app_timestamp"
                  + ", fac_export_app_flags"
                  + ") "
                  + "SELECT " + safe.quoted_sql(sectienaam)
                  + "     , 'From gen_export.ini '||" + safe.quoted_sql(sectienaam)
                  + "     , " + safe.quoted_sql(ExportCharset)
                  + "     , " + safe.quoted_sql(ExportFolder)
                  + "     , " + safe.quoted_sql(System)
                  + "     , " + safe.quoted_sql(ExportPrefix)
                  + "     , " + safe.quoted_sql(ExportPostfix)
                  + "     , " + safe.quoted_sql(ExportStyleSheet)
                  + "     , fac_functie_key"
                  + "     , " + safe.quoted_sql(LogPostfix)
                  + "     , " + safe.quoted_sql(BackupTimestamp)
                  + "     , " + Manual
                  + "  FROM fac_functie"
                  + " WHERE fac_functie_code = 'WEB_PRSSYS'"; // veilig
              //__Log(sql);
              Oracle.Execute(sql);
            }
            oRs.Close();
          } // if (ExportFolder && ExportPostfix)
        }
        // Verwijderen ini file ?
      }
      else
      {
        __Log("Conversion of " + genini + " not needed.");
      }
    }

    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 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 + " does already exist.";
            }
            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 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;
        }
        oRs.Close();
      }

      return result;
    }

    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);
      }
    }

  </script>
</job>
