<%@language = "javascript" %>
<% /*
    $Revision$
    $Id$

    File:           cad_verify.asp
    Description:    Analyseer de lagen van een dwf tekening
    Parameters:     dwf
                    concept (0/1)
    Context:
    Note:
*/
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file='../CAD/FGII.inc'-->

<%
user.checkAutorisation("WEB_PRSSYS");
if (Server.ScriptTimeout<600) Server.ScriptTimeout=600;

FCLTHeader.Requires({ plugins: [],
                    js: ["jQuery-ui.js"],
                    css: []});

var oAbout = new ActiveXObject("SLNKDWF.About");
tmStart = oAbout.usTimer;
FCLTHeader.Requires({ plugins: ["jQuery"] });

var concept = getQParamInt("concept", 0);
var dwf = getQParam("dwf", "");
var doanalyze = getQParamInt("analyze", 0) == 1; // probeer de optimale contour/label laag te vinden

var fullnameDWF = (concept==1?S("flexfilespath") + "/cad/concept/":concept==2?S("flexfilespath") + "/cad/symbols/":S("flexfilespath") + "/cad/") + safe.filename(dwf);
var fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(fullnameDWF))
    dwf = "";
else
{
    var fsoFile = fso.GetFile(fullnameDWF);
    var dtdwf = new Date(fsoFile.DateLastModified);
}

%>
<html>
  <head>
<%  FCLTHeader.Generate(); %>

    <script>
        $(function ()
        {
            $(".lcont").click(function () { $("#lcont").val($(this).text()); myRefresh() });
            $(".llabel").click(function () { $("#llabel").val($(this).text()); myRefresh() });
            $("#keeptemp,#hidenolabel,#markers,#process,#showorigin").change(function () { myRefresh() });
            $("#actueel,#concept,#symbool,#sDocuments").change(onOtherDrawing);
        });

        function init()
        {
            resizeIframes()
            MMap.Reset();
            MMap.SetIMGGenerator("../CAD/cad_verify_proc.asp");
            MMap.SetDWF("<%=safe.jsstring(fullnameDWF)%>"); // Voor Slnk2IMG.asp IMGgenerator
            MMap.SetPaperColor(<%=S("fg_paperColor")%>);
            MMap.SetLabelPosition(2);
            //MMap.Refresh(true); // Do zoom extents
            myRefresh();

<%          if (!S("fg_dwfviewer_installed")) { %>
                MMap.addButtonAfter("ImgPrint",
                                        { id:"dwf",
                                          alt:"Open DWF",
                                          label: L("lcl_slnk_dwfviewer"),
                                          onClick: onDwf,
                                          icon: "fa-file-export"
                                        });
<%            }%>
        }

        function onDwf(evt)
        {
            if (!evt) evt=window.event;

            FcltMgr.stopPropagation(evt);
            var url = "../CAD/cad_verify_proc.asp?AsDWF=1" + MMap.gCustomParameters;
            FcltMgr.windowopen(url,'FGShow');
        }
        function resizeIframes()
        {
            //var height = parseInt(document.documentElement.clientHeight);
            //document.getElementById('MMap').style.height = (height) +"px";
        }

        function MMap_onClick(SlnkEvent)
        {
            console.log(SlnkEvent);
            var txt = "Clicked X=" + Math.round(SlnkEvent.dwgX) + " Y=" + Math.round(SlnkEvent.dwgY);
            if (SlnkEvent.ContourKey)
                txt += " ({0})".format(SlnkEvent.ContourKey)
            $("#clicked").show().html(txt);
            return false; // Don't process
        }

        function doreload(analyze)
        {
            var sel = document.getElementById("sDocuments");
            var dwf = $("#sDocuments").val();
            var concept = $("input:radio[name=concept]:checked").val();
            window.location.href = "<%=Request.ServerVariables("SCRIPT_NAME")%>?dwf=" + dwf + "&concept="+concept + (analyze?"&analyze=1":"");
        }
        function onOtherDrawing(analyze)
        {
            doreload(false);
        }

        var contLayer = "<%=safe.jsstring(S("fg_contourlayers"))%>";
        var labelLayer = "<%=safe.jsstring(S("fg_labellayers"))%>";
        function myRefresh()
        {
            var custParam= "&dwf=<%=safe.jsstring(dwf)%>"
                         + "&concept=<%=concept%>"
                         + "&layers=" + $('select#layers>option:selected').map(function(){ return this.text }).get().join(",");;
            if ($("#lcont").val() && $("#llabel").val())
                custParam += "&contLayer="+$("#lcont").val()
                           + "&labelLayer="+$("#llabel").val();
            if ($("#keeptemp").prop("checked"))
                custParam += "&keeptemp=1";
            else
                $("#tempname").text("");
            if ($("#showorigin").prop("checked"))
                custParam += "&showorigin=1";
            var markers = $("#markers").children("option:selected").val();
            custParam += "&markers=" + markers; // elke 150px
            if ($("#hidenolabel").prop("checked"))
                custParam += "&shownolabel=0";
            if ($("#process").prop("checked"))
            {
                MMap.SetIMGGenerator("../CAD/cad_verify_proc.asp");
            }
            else
            {
                MMap.SetIMGGenerator("../SlnkDWF/Slnk2IMG.asp");
                MMap.SetDWF("<%=safe.jsstring(fullnameDWF)%>");
            }
            MMap.SetCustomParameters(custParam)
            MMap.Refresh(); // Try not to zoom extents
        }

        function MMap_onMapperLoad(pSLNKEvent)
        {
          if (pSLNKEvent && pSLNKEvent.success)
          {
              var accuracy = -(Math.log(pSLNKEvent.scaleX)/Math.log(10));
              if (accuracy<0) accuracy = 0;
              version =  " DWG ("+pSLNKEvent.viewminX.toFixed(accuracy)+", "+pSLNKEvent.viewminY.toFixed(accuracy) +")";
              version +=   " - ("+pSLNKEvent.viewmaxX.toFixed(accuracy)+", "+pSLNKEvent.viewmaxY.toFixed(accuracy) + ")";

              var dx = (pSLNKEvent.viewmaxX-pSLNKEvent.viewminX) / <%=S("fg_dwgscale")%>;
              var dy = (pSLNKEvent.viewmaxY-pSLNKEvent.viewminY) / <%=S("fg_dwgscale")%>;
              var unit = "m";
              var area = dx * dy; // die altijd in meters laten
              if (dx < 5)
              {
                dx *= 1000;
                dy *= 1000;
                unit = "mm";
                accuracy = -1;
              }

              version += " = " + dx.toFixed(accuracy+1)+ " x "+ dy.toFixed(accuracy+1) + unit;
              version += " = " + area.toFixed(area>100?0:area>10?1:2) + "m&sup2;";

              if (window.DWG2LP)
              {
                var INT_MIN = -2147483648;
                var INT_MAX = 2147483647;
                //scx : (INT_MAX - INT_MIN) / (res.DwgLimits.max.DwgX - res.DwgLimits.min.DwgX)
                //console.log(DWG2LP);
                var LPx1 = INT_MIN + (pSLNKEvent.viewminX -  DWG2LP.minx) * DWG2LP.scx;
                var LPx2 = INT_MIN + (pSLNKEvent.viewmaxX -  DWG2LP.minx) * DWG2LP.scx;
                var LPy1 = INT_MIN + (pSLNKEvent.viewminY -  DWG2LP.miny) * DWG2LP.scy;
                var LPy2 = INT_MIN + (pSLNKEvent.viewmaxY -  DWG2LP.miny) * DWG2LP.scy;
                version += "<br>DWF (" + Math.round(LPx1) + ", " + Math.round(LPy1) + ") - (" + Math.round(LPx2) + ", " + Math.round(LPy2) + ")";
                version += " = " + Math.round(LPx2 - LPx1) + " x " + Math.round(LPy2 - LPy1);
              }
              if (pSLNKEvent.tempfile)
                version = pSLNKEvent.tempfile + "<br>" + version;
              $('#extents').html(version);
          }
        }
        function Report()
        {
            var url = "<%= "appl/cad/cad_verify_report.asp?dwf={0}&concept={1}".format(safe.url(dwf), concept) %>";
            FcltMgr.openDetail(url, "<%=safe.jsstring(dwf)%>");
        }
    </script>

    <style>
        table#analyze td { border: 1px solid black; }
        xlabel { width: 40px; }
        .lcont, .llabel { cursor: pointer;
                          white-space: nowrap; }
        input#lcont,input#llabel { width: 180px; }
        table#analyze td sup {
            color:#888;
        }
    </style>
</head>

<body class="editmode" id="cadverifybody" <%=dwf==""?"x":""%>onLoad='init();'>
<%
var buttons = [];
if (dwf)
    buttons.push({ icon: "fa-fclt-refresh", title: 'Report', action: "Report()" }); //geen lcl
buttons.push({ icon: "fa-fclt-refresh", title: L("lcl_refresh"), action: "FcltMgr.reload()" });

HAMBUTTONS = []; // ik wil ze altijd zien
IFRAMER_HEADER("Verify DWF files", buttons);

var ttl = "Choose a drawing";
if (dwf)
    ttl = "Viewing {0} (uploaded {1})".format(dwf, toISODateTimeString(dtdwf));

if (concept==1 && !dwf) {
    Response.Write("<div style=\"width: 20em;\">" + FILEPICKER_HTML("concept", "Upload concept", null, { "module": "FGII_M", "key": 0, "defaultValue": "Upload concept", "icon": "fa-compass-drafting" }) + "</div>");
}

%><label for="actueel"><input type="radio" id='actueel' name='concept' value='0' <%=concept==0?"checked":""%>><%=L("lcl_fg_actueel")%></label>
  <label for="concept"><input type="radio" id='concept' name='concept' value='1' <%=concept==1?"checked":""%>><%=L("lcl_fg_concept")%></label>
  <label for="symbool"><input type="radio" id='symbool' name='concept' value='2' <%=concept==2?"checked":""%>><%=L("lcl_fg_symbols")%></label>
    <%= S("flexfilespath") + "/cad/" + (concept?"concept/":"")%>
        <select id="sDocuments" class="<%=dwf ? "fld" : "fldmulti"%>" style="width:300pt;vertical-align:top" size="<%=dwf?1:20%>"<%=dwf ? "" : " multiple"%>>
<%
      pathName = S("flexfilespath") + "/cad/" + (concept==1?"concept/":concept==2?"symbols/":"");
      fso = new ActiveXObject("Scripting.FileSystemObject");
      if (fso.FolderExists(pathName) )
      {
         f1 = fso.GetFolder(pathName);
         fc4 = new Enumerator(f1.files);
         for (; !fc4.atEnd(); fc4.moveNext())
         {
             vTekening0 = fc4.item().Name;
             if (vTekening0.match(/\.dwf$/i)||vTekening0.match(/\.w2d$/))
             {
                var dt = new Date(fc4.item().DateLastModified);
%>    <option <%=vTekening0==dwf?"selected='1'":""%> value='<%=safe.htmlattr(vTekening0)%>' title='<%=toISODateTimeString(dt)%>'><%= safe.html(vTekening0)%></option>
<%
             }
         }
      }
%></select><%
if (dwf=="")
{
    //Response.Write(safe.html(fullnameDWF));
    Response.End;
}

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.dwgScale=10
xc.SetDimensions(1200,800, 0, 0, 1, 180)
var dummy = xc.GetAsMAP(); // om een parse to forceren!

var layers = [];
//Response.Write("Lagen: " + xc.layerCount);
for (i = 0; i < xc.layercount; i++)
    layers[xc.LayerItem(i)] = 1;

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

    y.minmergedistance = S("fg_minmergedistance"); // mm

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

    var result = { nCont: y.ContourCount,
                   Labels: [],
                   UnmatchedLabels: y.UnmatchedLabels,
                   Opp: 0,
                   vectordpi: y.vectordpi, // sinds 4,18
                   DwgLimits: y.DwgLimits // sinds 4,xxxx
                 };
    var m2 = 0;
    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("{0}<sup>({1})</sup>".format(oLabel, oOpp.toFixed(1)));
            result.Opp += oOpp;
        }
        //else if (oOpp > S("fg_contour_minArea") / 1e6)
        //{
        //    result.Labels.push("<span style='color:red'>{0}</span><sup>({1})</sup>".format('??', oOpp.toFixed(1)));
        //    result.Opp += oOpp;
        //}
        //Response.Write((oLabel) + ": " + oOpp);
    }

    return result;
}
function prettyXML(xml)
{
    var objxml = new ActiveXObject("MSXML2.DOMDocument.6.0");
    objxml.loadXML(xml);
    if (objxml.parseError.errorCode)
    {
      return ("XSL error: " + objxml.parseError.reason + " @ " + objxml.parseError.line + "." + objxml.parseError.linepos  + "\n"+  objxml.parseError.srcText);
    }
    var style = new ActiveXObject("MSXML2.DOMDocument.6.0");
    style.async = false;
    style.load(Server.MapPath(rooturl + "/appl/shared/indent.xsl"));
    return objxml.transformNode(style).replace(/\x0D\x0A\s*\x0D\x0A/g,'\x0D\x0A');
}
if (!xd.EplotSections.Count)
    Response.Write("<p style='color:red'>Strange, no EPlotSections. DWF not created with AutoCAD?</p>");
else
{
    if (!epl.Title.match(/Model$/i))
        Response.Write("<p style='color:red'>Strange, plotsection is not named 'Model' but '{0}'.\nPerhaps exported from paperspace layout?</p>".format(epl.Title));
}
if (!xc.layercount)
{
    Response.Write("<p style='color:red'>DWF has no layerinfo!</p>");
    layers[".*"] = 1;
}
else
    Response.Write("<p></p>");
%>
    <table><tr><td>
        <iframe id=MMap name=MMap src="../SlnkDWF/ToonIMG.asp?ShowButtons=1"
            frameborder='0' framespacing='0' scrolling=no
            style="border:1px solid blue" width="800"  height="600">
        </iframe>

    <table><tr><td>
        <label for='keeptemp'><input type='checkbox' id='keeptemp'>Keep temp</label><span id='tempname'></span><br>
        <label for='process'><input type='checkbox' id='process' checked='1'>Process contouren</label><br>
    <% if (oAbout.VersionString >= "4,21") { %>
        <select id='markers' class='fld' style='width:155px'>
                <option value='0'>Show DWF coordinates</option>
                <option value='150'>Every 150px</option>
                <option value='50'>Every 50px</option>
                <option value='1'>Auto (zoomed in)</option>
        </select>
<% } %>
        <label for='showorigin'><input type='checkbox' id='showorigin'>Show origin</label><br>
        </td>
        <td><div id='extents'></div>
            <span id='clicked' style='display:none'>Hier komen geklikte coördinaten</span>
        </td>
    </tr></table>
    </td>
    <td valign='top'>
        <table>
            <tr>
                <td colspan="2">
                    <button onclick='myRefresh()'>&lArr; Update</button>
                    <button onclick='$("#lcont,#llabel").val("");myRefresh()'>Clear &dArr;</button>
                    <button onclick='$("#lcont").val(contLayer);$("#llabel").val(labelLayer);myRefresh()'>Default &dArr;</button><br>
                </td>
            </tr>
            <tr>
                <td class='label'>
                    <label for='lcont'>Cont</label>
                </td>
                <td>
                    <input id='lcont' class='fld' type='text' value='<%=safe.htmlattr(S("fg_contourlayers"))%>'>
                </td>
            </tr>
            <tr>
                <td class='label'>
                    <label for='llabel'>Label</label>
                </td>
                <td>
                    <input id='llabel' class='fld' type='text' value='<%=safe.htmlattr(S("fg_labellayers"))%>'>
                </td>
            </tr>
            <tr>
                <td colspan='2'>
                    <select id='layers' class='fldmulti' multiple='1' size='24' onchange='myRefresh()'><option>__geen__</option>
                        <%
                            var ll = [];
                            for (layer in layers)
                                ll.push(layer.toUpperCase());
                            ll.sort();
                            for (layer in ll)
                                Response.Write("<option selected='1'>"+safe.html(ll[layer])+"</option>");
                        %>
                    </select>
                </td>
            </tr>
        </table>
        (<%=xc.layercount%> layers in total)
        <br><span style='background-color:#C4E4DF;padding:3px;border:2px solid #888;'>contours with label</span>&nbsp;
            <span style='background-color:#ABE7C3;padding:3px;border:2px solid #888;'>contours overlapping</span>
        <br><span style='background-color:#FF0000;color:#fff;padding:3px;border:2px solid #888;'>contours without label</span>
            <input type='checkbox' id='hidenolabel'><label for='hidenolabel'>hide</label>

    </td></tr></table>
<%
var res = {};
var contlayers = [];
var labellayers = [];
var lastcont="";
if (doanalyze)
{
    // Bepaal voor elke laag hoeveel contouren het zou opleveren
    for (contlayer in layers)
    {
        var res = analyze(contlayer, ".*")
        if (res.nCont)
        {
            contlayers.push({ l: contlayer, n: res.nCont});
            //Response.Write("<br>C:"+contlayer + " n:"+res.nCont)
        }
    }
    for (labellayer in layers)
    {
        var res = analyze(".*", labellayer, ".*")
        if (res.Labels.length)
        {
            labellayers.push({ l: labellayer, n: res.Labels.length});
            //Response.Write("<br>L:"+labellayer + " n:"+res.Labels.length)
        }

    }
}
else
{
    var res = analyze(S("fg_contourlayers"), S("fg_labellayers"))
    if (res.nCont)
        contlayers.push({ l: S("fg_contourlayers"), n: res.nCont});
    if (res.Labels.length)
        labellayers.push({ l: S("fg_labellayers"), n: res.Labels.length});
}

if (xd.EplotSections.Count)
{
%>
<button onclick="$('pre#xd').toggle()">DWF manifest</button><pre id='xd' style='display:none'><%= Server.HTMLEncode(prettyXML(xd.PropertiesXML)) %></pre>
<button onclick="$('pre#res').toggle()">Plotsection manifest</button> <pre id='res' style='display:none'><%= Server.HTMLEncode(prettyXML(epl.PropertiesXML)) %></pre>
<% }
if (res.vectordpi > 0)
{
    Response.Write("DPI: " + res.vectordpi);
    if (res.vectordpi < 4800)
        Response.Write(" (exporting using 4800 gives better resolution)");
}
if (res.DwgLimits)
{
    var INT_MIN = -2147483648;
    var INT_MAX = 2147483647;
    Response.Write(", DWG Limits: ({0}, {1})-({2}, {3})".format(Math.round(res.DwgLimits.min.DwgX), Math.round(res.DwgLimits.min.DwgY),
                                                                  Math.round(res.DwgLimits.max.DwgX), Math.round(res.DwgLimits.max.DwgY)));
    var DWG2LP = { scx : (INT_MAX - INT_MIN) / (res.DwgLimits.max.DwgX - res.DwgLimits.min.DwgX),
                   scy : (INT_MAX - INT_MIN) / (res.DwgLimits.max.DwgY - res.DwgLimits.min.DwgY),
                   minx: res.DwgLimits.min.DwgX,
                   miny: res.DwgLimits.min.DwgY
                 };
    Response.Write("\n<script>var DWG2LP = JSON.parse('{0}');</script>".format(safe.jsstring(JSON.stringify(DWG2LP))));
}
// nu matchen
%><div>Area Threshold: <%= (S("fg_contour_minArea")/1e6).toFixed(2) %>m<sup>2</sup> <span style='font-size:0.8em'>omdat S("fg_contour_minArea") = <%= S("fg_contour_minArea") %>mm<sup>2</sup></span></div><%

if (!doanalyze)
{
    Response.Write("Analyzed using default setting fg_contourlayers {0} and fg_labellayers {1} ".format(safe.html(S("fg_contourlayers")), safe.html(S("fg_labellayers"))));
    Response.Write("<button onclick='doreload(true)'>Analyze all layers</button><br>");
}

Response.Write("<table id='analyze' border=1>");
Response.Write("<tr><th>fg_contlayer</th><th>#cont</th><th>fg_labellayer</th><th>#label</th><th>Opp.</th><th>Labels</th></tr>");
for (contlayer in contlayers)
{
    cl = contlayers[contlayer];
    for (labellayer in labellayers)
    {
        ll = labellayers[labellayer];
        var res = analyze(cl.l, ll.l)
        if (res.Labels.length)
        {
            Response.Write("<tr><td class='lcont'>"+(lastcont==cl.l?"":cl.l) + "</td>"
                          +"<td>" + (lastcont==cl.l?"":res.nCont) + "</td>");
            Response.Write("<td class='llabel'>" + ll.l + "</td>"
                          +"<td>" + res.Labels.length + (res.Labels.length == ll.n?"":("/"+ll.n)) + "</td>"
                          +"<td style='text-align:right'>" + res.Opp.toFixed(1) + "m²</td>");
            Response.Write("<td>" + res.Labels.join(" "));
            if (res.UnmatchedLabels)
            {
                var cnt = res.UnmatchedLabels.split("\n").length;
                Response.Write("<br>No contour for: <span style='background-color:#dfd'>" + (cnt<10?res.UnmatchedLabels:(cnt + " labels")) + "</span>");
            }
            Response.Write("</td></tr>");
            lastcont=cl.l;
        }
    }
}
Response.Write("</table>");
%>
<small>This page: <%= ((oAbout.usTimer - tmStart)/1000).toFixed() %>ms for <%=contlayers.length%> * <%=labellayers.length%> combinations,
       (<%=oAbout.DLLPath%>, <%=oAbout.VersionString%>, <%=oAbout.Buildtime%>)
</small>
  </body>
</html>
<% ASPPAGE_END(); %>
