/*
    $Revision$
    $Id$

    File:               exp_shared.js
    Description:        Helper functie
    Parameters:
        export_app_key  Exportfunctie key
    Context:
    Note:               ========= LET OP LET OP =========
                        Dit bestand wordt ook gebruikt door ../../utils/gen_export/gen_export.wsf
                            Daar hebben we door CScript maar heel weinig functies!
                            DUS: Geen L() functie voor locale!!!!
                             EN: Geen Server.CreateObject maar new ActiveXObject
                             EN: Slechts enkele functies van safe.
                        ========= LET OP LET OP =========

                        gen_export_app_flags: 00001 (1)  zip het resultaat
                                              00010 (2)  manual allowed (future use)
*/

// fileStream moet onze data bevatten
// export_app_key de export-functie
// params export_key mag/zal leeg zijn voor het eerste bestand
//        custid: "UWVA"
//        fac_home: net boven de APPL dus bijv. "d:/apps/facilitor/"
//        filepathname: optioneel: stoppen we in fac_export_filenaam
function expCreateStream(export_key, params)
{
    preExport(params);
    var exportFile = getFileName(params.fileprefix, params.postfix, params.applrun, params.timestamp);
    var streamData = exportToStream(params, exportFile); // exportFile voor als compress
    if (!params.preview)
        postExport(params);

    if (params.compress)
        exportFile += '.zip';

    return { exportFile: exportFile
           , streamData: streamData
           };
}


function getSettings(app_key)
{
    // Read settings from database
    //
    var settings = {};
    var sql = "SELECT *"
            + "  FROM fac_export_app"
            + " WHERE fac_export_app_key = " + app_key;
    var oRs = Oracle.Execute(sql);
    if (oRs.Eof)
    {
        __Log("Unable to find " + app_key + " in fac_export_app");
    }
    else
    {
        settings = { code: oRs("fac_export_app_code").value
                   , oms:  oRs("fac_export_app_oms").value
                   , xsl:  oRs("fac_export_app_xsl").value || ""
                   , charset: oRs("fac_export_app_charset").value || "Windows-1252"
                   , folder:  oRs("fac_export_app_folder").value  || ""
                   , prefix:  oRs("fac_export_app_prefix").value  // straks fallback naar params.custid die we hier nog niet hebben
                   , postfix: oRs("fac_export_app_postfix").value || ""
                   , timestamp:   oRs("fac_export_app_timestamp").value || ""
                   , flags:   oRs("fac_export_app_flags").value || 0
                   , functie_key: oRs("fac_functie_key").value || -1
                   , logpostfix: oRs("fac_export_app_log_postfix").value || ""
                   , fileprefix: oRs("fac_export_app_file_prefix").value || ""
                   }
    }
    oRs.Close();
    if (settings.flags & 1)
        settings.compress = true;
    if (settings.flags & 2)
        settings.manual = true;
    return settings;
}


function preExport(params)
{
    // Clean up the mess of the previous run
    //
    var sql = "DELETE FROM imp_log"
            + " WHERE imp_log_applicatie = " + safe.quoted_sql(params.code);
    __Log("SQL: " + sql);
    Oracle.Execute(sql);
    //
    // Call the database procedure for selecting the export results.
    var selectProc = (params.prefix||params.custid) + "_SELECT_" + params.code;
    var sql = "SELECT DISTINCT name"
            + "  FROM user_source"
            + " WHERE type = 'PROCEDURE'"
            + "   AND name = " + safe.quoted_sql(selectProc.toUpperCase());
    __Log("SQL: " + sql);
    var oRs = Oracle.Execute(sql);
    if(!oRs.Eof)
    {
        sql = "BEGIN " + selectProc + "(" + safe.quoted_sql(params.code) + ", " + safe.quoted_sql(toDateTimeString(params.applrun)) + "); END;";
        __Log("SQL: " + sql);
        Oracle.Execute(sql);
    }
    else
    {
        __Log("Optional select/pre-export procedure not found: " + selectProc);
    }
    oRs.Close();
}

function postExport(params)
{
  // Call the database procedure for creation of exportfile.
  var filename = getFileName(params.fileprefix, params.postfix, params.applrun, params.timestamp);
  var exportProc = (params.prefix||params.custid) + "_EXPORT_" + params.code;
  var sql = "SELECT DISTINCT name"
          + "  FROM user_source"
          + " WHERE type='PROCEDURE'"
          + "   AND name = " + safe.quoted_sql(exportProc.toUpperCase());
  __Log("SQL: " + sql);
  var oRs = Oracle.Execute(sql);
  if (!oRs.Eof)
  {
    var sql = "BEGIN "
            + exportProc + "(" + safe.quoted_sql(params.code)
                         + "," + safe.quoted_sql(toDateTimeString(params.applrun))
                         + ",'-1'"                            //+ safe.quoted_sql(iniOraclePath)  // ??
                         + "," + safe.quoted_sql(filename)
                         + ");"
            + " END;"
    __Log("SQL: " + sql);
    Oracle.Execute(sql);
  }
  else
  {
    __Log("Optional (post-)export procedure not found: " + exportProc);
  }
  oRs.Close();
}

// Lever null op als er geen select-view is gedefinieerd.
function exportToStream(params, exportFile)
{
    var fstr;
    var exportView = (params.prefix||params.custid) + "_V_EXPORT_" + params.code;
    var sql = "SELECT DISTINCT view_name"
            + "  FROM USER_VIEWS"
            + " WHERE view_name = " + safe.quoted_sql(exportView.toUpperCase());
    __Log("SQL: " + sql);
    var oRs = Oracle.Execute(sql);
    if (oRs.Eof)
    {
        __Log("Optional export view not found: " + exportView);
        oRs.Close()
        return null;
    }
    else
    {
        // Write data to stream.
        fstr = openStreamWriteText({charset: params.charset});
        var sql_v = "SELECT result"
                  + "  FROM  " + exportView
                  + " ORDER BY result_order";
        __Log("SQL: " + sql_v);
        var oRs_v = Oracle.Execute(sql_v);
        while (!oRs_v.Eof)
        {
            fstr.WriteText(oRs_v("result").Value, 1); // 0=adWriteChar, 1=adWriteLine (LineSeparator required)
            oRs_v.MoveNext();
        }
        oRs_v.Close();
    }
    oRs.Close();
    fstr.Position = 0;

    if (!params.compress)
        return fstr;

    var oZIP = new ActiveXObject("SLNKDWF.Zip");
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var temp = params.tempFolder + fso.GetTempName();
    oZIP.New(temp) //;; Helaas niet *naar* stream
    oZIP.ZipFromStream(exportFile, fstr);
    oZIP.Close();
    var oStream = new ActiveXObject("ADODB.Stream");
    oStream.Open;
    oStream.Type = 1; // adTypeBinary

    oStream.LoadFromFile(temp);
    oStream.Position = 0;
    fso.DeleteFile(temp);
    return oStream;
}


function openStreamWriteText(params)
{
    // params:
    //   lineseparator: -1=adCRLF, 10=adLF, 13=adCR
    //   streamwrite:   1=adSaveCreateNotExist, 2=adSaveCreateOverWrite
    //   charset:
    // var streamwrite = (params.streamwrite ? params.streamwrite : 1);

    var fileStream = new ActiveXObject("ADODB.Stream");
    fileStream.CharSet = (params.charset ? params.charset : "Windows-1252");
    fileStream.LineSeparator = (params.lineseparator ? params.lineseparator : -1);
    fileStream.Type = 2; // 1=adTypeBinary, 2=adTypeText
    fileStream.Open();

    return fileStream;
}


function getFileName(fileprefix, postfix, daterun, dateformat)
{
    var index = fileprefix.indexOf(".");
    var naam = (index==-1?fileprefix:fileprefix.substr(0, index)) + formatDate(daterun, dateformat) + postfix;
    return naam;
}


function formatDate(datum, format)
{
    var onejan = new Date(datum.getFullYear(),0,1);
    var o = { "m+" : datum.getMonth()+1                  //month
            , "d+" : datum.getDate()                     //day
            , "H+" : datum.getHours()                    //hour
            , "M+" : datum.getMinutes()                  //minute
            , "S+" : datum.getSeconds()                  //second
            , "q+" : Math.floor((datum.getMonth()+3)/3)  //quarter
            , "s"  : datum.getMilliseconds()             //millisecond
            , "w+" : Math.ceil((((datum - onejan) / 86400000) + onejan.getDay()+1)/7) // weeknumber
            };
    format = format.replace('hhmm', 'HHMM');
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (datum.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
    {
        if(new RegExp("("+ k +")").test(format))
        {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}

