/*
    $Revision$
    $Id$

    File:           cad_verify_report.asp.asp
    Description:    Genereer een rapportage over dit dwf bestand
    Parameters:     dwf
                    concept (0/1)
    Context:
    Note:           Dit bestand wordt duaal gebruik!
                    Enerzijds van cad_verify_report.asp (die vanuit de interface het rapport toont)
                    Anderzijds is het los aan te roepen met
                        CScript cad_verify_report.js /path/to/filename.dwf [contourlayers] [labellayers]

                    LET OP: omdat het ook vanuit CScript.exe moet werken kun je geen gebruik maken van de database
                            In het bijzonder mag je L() en S() niet gebruiken!
                            Zelfs vanuit cad_verify_report.asp mag dat niet omdat de ASPPAGE_END(); daaruit
                            de Oracle database al gesloten heeft.
*/

if (!this.Server) // dan zitten we in CScript.exe
{
    var oStream = new ActiveXObject("ADODB.Stream");
    oStream.Open;
    oStream.Charset = "Windows-1252";
    oStream.Type = 2; // Text
    /* geen var */ Response = { Write: function(s) { oStream.WriteText(s); } }

    var fg_contourlayers = "{00---0--FM-RUIMTEDEFN.*}";
    var fg_labellayers = "{00---0--FM-RUIMTENR.*}";
    if (WScript.Arguments.length < 1)
    {
      WScript.Echo("Usage: CScript cad_verify_report.js /path/to/filename.dwf [contourlayers] [labellayers]");
      WScript.Echo("       default contour layers: " + fg_contourlayers);
      WScript.Echo("               label layers  : " + fg_contourlayers);
      WScript.Echo("Batchfile tip: for %%f in (*.dwf) do cscript w:\\Branch20202\\APPL\CAD\\cad_verify_report.js %%f");
      WScript.Quit();
    }

    var fullnameDWF = WScript.Arguments(0);
    var dwf = fullnameDWF.split(/\\\//).pop();
    if (WScript.Arguments.length >= 2)
    {
        var fg_contourlayers = WScript.Arguments(1);
        var fg_labellayers = WScript.Arguments(2);
    }

    var fg_contour_minArea = 200010;
    var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
    var rnd = oCrypto.hex_random(10);
    var tempW2D = "./CAD_" + oCrypto.hex2base64(rnd, false, true) + ".w2d";
    Response.Write("<!DOCTYPE html>");

    // Dubbelop: een aantal functies voor als je dit met CScript draait
    String.prototype.format = function()
    {
        var formatted = this;
        for (var i = 0; i < arguments.length; i++)
        {
            if (typeof arguments[i] == "string")
              arguments[i] = arguments[i].replace(/\$/g, '$$$$');
            var regexp = new RegExp('\\{'+i+'\\}', 'gi');
            formatted = formatted.replace(regexp, arguments[i]);
        }
        return formatted;
    };
    function padout(number) { return (number < 10) ? "0" + number : number; }
    function toISODateString(jsDate)
    {
        return padout(jsDate.getFullYear())  + "-" + padout(jsDate.getMonth() + 1) + "-" + padout(jsDate.getDate());
    }

    function toISODateTimeString(jsDate)
    {
        if (typeof jsDate == "number")
            jsDate = new Date(jsDate);

        if (typeof jsDate == "object" && jsDate.type == 135/*adDBTimeStamp, oRs("datum")*/)
            jsDate = new Date(jsDate.value);

        if (typeof jsDate == "date") // een oRs("datum").value
            jsDate = new Date(jsDate);

        return toISODateString(jsDate) + " "
             + padout(jsDate.getHours()) + ":" + padout(jsDate.getMinutes())   + ":" + padout(jsDate.getSeconds());
    }
    safe = { // extracted from shared.inc
        html: function (tekst) // maxlen is optioneel
        {
            return tekst;
        },
        filename: function (naam) // geen 'lage' karakters een geen (back)slashes, *,%,<,>, '"', ':', '?' and '|'
        {
            return naam.replace(/[\x00-\x1F|\/|\\|\*|\%\<\>\"\:\;\?\|]+/g, "_"); // " syntax highlight correctie
        }
    }

}
else
{
    var concept = getQParamInt("concept", 0) == 1;
    var dwf = getQParam("dwf");

    var fullnameDWF = (concept?S("flexfilespath") + "/cad/concept/":S("flexfilespath") + "/cad/") + safe.filename(dwf);
    var tempW2D = shared.tempFolder() + "/CAD_" + shared.random(16) + ".w2d";

    var fg_contour_minArea = S("fg_contour_minArea");
    var fg_minmergedistance = S("fg_minmergedistance");
    var fg_flags = S("fg_slnkdwf_flags");
    var fg_contourlayers = S("fg_contourlayers");
    var fg_labellayers = S("fg_labellayers");
}


var oAbout = new ActiveXObject("SLNKDWF.About");
tmStart = oAbout.usTimer;

var fso = new ActiveXObject("Scripting.FileSystemObject");
var fsoFile = fso.GetFile(fullnameDWF);
var dtdwf = new Date(fsoFile.DateLastModified);

Response.Write("<html>");
Response.Write("  <head>");
Response.Write('<meta http-equiv="Content-Type" content="text/html;charset=windows-1252">');
Response.Write("    <style>");
Response.Write("        body {");
Response.Write("            font-family: verdana, arial, helvetica, sans-serif;");
Response.Write("            font-size: 0.75em;");
Response.Write("            line-height: 1.8em;");
Response.Write("        }");
Response.Write("        img.dwf { border: 1px solid blue; }");
Response.Write("    </style>");
Response.Write("</head>");
Response.Write("<body id='cadverifybody'>");

Response.Write("<h2>DWF {0}</h1>".format(dwf));
try
{
    var xd = new ActiveXObject("SLNKDWF.DWFFile");
    xd.Open(fullnameDWF);
    var xc = new ActiveXObject("SLNKDWF.Whip2PNG")
    if (xd.EplotSections.Count == 0)
        xc.Load(fullnameDWF);
    else
    {
        var epl = xd.EplotSections.Item(0);
        xc.LoadStream(epl);
    }
}
catch (e)
{
    shared.simpel_page("Error opening " + fullnameDWF + "<br>" + e.description);
}

xc.Maximize=true;
xc.SetDimensions(800,600, 0, 0, 1)
var dummy = xc.GetAsMAP(); // om een parse to forceren!

function analyze(contlayer, labellayer)
{
    var y = new ActiveXObject("SLNKDWF.WhipFile")

    y.minContSize = fg_contour_minArea;
    y.minmergedistance = fg_minmergedistance;
    y.flags = fg_flags;

    //y.SetLayers("^"+contlayer.replace(/\|/g,"\\|")+"$", "^"+ labellayer.replace(/\|/g,"\\|")+"$")
    y.SetLayers(contlayer, labellayer)
    if (xd.EplotSections.Count == 0)
        y.Load(fullnameDWF);
    else
        y.LoadStream(xd.EplotSections.Item(0));

    var result = { nCont: y.ContourCount,
                   Labels: [],
                   Opp: 0,
                   vectordpi: y.vectordpi, // sinds 4,18
                   DwgLimits: y.DwgLimits, // sinds 4,xxxx
                   whipfile: y
                 };
    for (var i2=0; i2 < y.ContourCount; i2++)
    {
        var c = y.ContourItem(i2);
        var oLabel = c.Key;
        var oOpp =   c.Area / 1e6; // Vanuit de DLL krijg ik altijd mm2 lijkt het?
        if (oLabel && oOpp)
        {
            result.Labels.push({l:oLabel, o: oOpp });
            result.Opp += oOpp;
        }
        else if (oOpp > fg_contour_minArea / 1e6)
        {
            result.Labels.push({l: "No label found", o: oOpp });
            result.Opp += oOpp;
        }
    }

    return result;
}
var res = analyze(fg_contourlayers, fg_labellayers);

if (!xd.EplotSections.Count)
    Response.Write("<p style='color:red'>Strange, no EPlotSections. DWF not created with AutoCAD?</p>");
if (!xc.layercount)
{
    Response.Write("<p style='color:red'>DWF has no layerinfo!</p>");
}

Response.Write("DWF uploaded {0}".format(toISODateTimeString(dtdwf)));

if (res.vectordpi > 0)
{
    Response.Write("<br>Vector DPI: " + res.vectordpi);
    if (res.vectordpi < 4800)
        Response.Write(" (exporting using 4800 gives better resolution)");
}

Response.Write("<h2>Scanning for rooms</h2>");

if (!res.Labels.length)
    Response.Write("<p style='color:red'>No labels detected!</p>");

Response.Write("Searching polylines on layer: {0} ==> {1} found<br>".format(safe.html(fg_contourlayers), res.whipfile.ContourCount));
Response.Write("Searching labels on layer: {0} ==> {1} found<br>".format(safe.html(fg_labellayers), res.Labels.length));
Response.Write("Area Threshold: {0}m<sup>2</sup>".format((fg_contour_minArea/1e6).toFixed(2)));
Response.Write("<table id='analyze' border=1>");
Response.Write("<tr><th>Label</th><th>Area mē</th></tr>");

for (var i = 0; i < res.Labels.length; i++)
{
    var label = res.Labels[i]
    Response.Write("<tr><td>{0}</td><td style='text-align: right'>{1}</td></tr>".format(label.l, label.o.toFixed(1)));
}
Response.Write("</table>");
Response.Write("Total " + res.Opp.toFixed(1) + " mē");


function stream2base64(str)
{
    var oStream = new ActiveXObject("ADODB.Stream");
    oStream.Open;
    oStream.Type = 1; // adTypeBinary
    oStream.Write(str);
    oStream.Position = 0;

    var oXML = new ActiveXObject("Msxml2.DOMDocument.6.0");
    var oNode = oXML.createElement("encodeddata");
    oNode.dataType = "bin.base64";
    oNode.nodeTypedValue = oStream.read(oStream.Size);
    var b64text = oNode.text.replace(/\n/g, ""); // Ik wil de newlines er niet in hebben
    oStream.Close();
    return b64text;
}
Response.Write("<h2>Original drawing</h2>");
Response.Write("<img class='dwf' src='data:image/png;base64, {0}' />".format(stream2base64(xc.GetAsPNG())));

Response.Write("<h2>Processed drawing (recognized rooms only)</h2>");

res.whipfile.SetLabelFont("Tahoma", 800)
for (var i2=0; i2 < res.whipfile.ContourCount; i2++)
{
    c = res.whipfile.ContourItem(i2);
    if (c.Key)
    {
        var opp = (c.Area / 1e6).toFixed(1);
        if (c.Area && opp < 5.0)
            c.Label = "[u][s75]" + c.Key + (c.Area?"\n[c][s35]("+ opp + "mē)":"");
        else
            c.Label = "[u]" + c.Key + (c.Area?"\n[c][s75]("+ opp + "mē)":"");
        c.SetColor(0x00FF00, 32);
    }
    //c.setcolor(0x00ff00);
    c.lineweight = 250;
    c.labelPosition = 2; // center
}

res.whipfile.SetFilterLayers("{SLNK Labels}|{SLNK Contours}|{SLNK Symbols}|{SLNK Symbol Labels}")
res.whipfile.SaveAs(tempW2D)

var xc2 = new ActiveXObject("SLNKDWF.Whip2PNG")
xc2.Load(tempW2D);
xc2.Maximize=true;
xc2.PaperColor=(0); //' Anders zien we de label zo slecht...
xc2.PaperColor = 0xFFFFFF;
xc2.SetDimensions(800,600, 0, 0, 1);
Response.Write("<img class='dwf'  src='data:image/png;base64, {0}' />".format(stream2base64(xc2.GetAsPNG())));
fso.DeleteFile(tempW2D);

Response.Write("<h2>Detected {0} layers</h2>".format(xc.layercount));
var ll = [];
for (i = 0; i < xc.layercount; i++)
    ll.push(xc.LayerItem(i).toUpperCase());
ll.sort();
for (layer in ll)
    Response.Write("&nbsp;&nbsp;{0}<br/>".format(safe.html(ll[layer])));

Response.Write("<small>Generated on {0} in {1}ms</small>".format(toISODateTimeString(new Date()), ((oAbout.usTimer - tmStart)/1000).toFixed()));

Response.Write("</body>");
Response.Write("</html>");

if (!this.Server)
{
    oStream.SAveToFile(fullnameDWF + ".html", 2);
    WScript.Echo("Created " + fullnameDWF + ".html");
}
