<?php
$pageTitle = "Logs";
include realpath(__DIR__) . '/../_common/header.php'; ?>
<script type="text/javascript">
let headers=['Name','Size','Modified'];
let cellTemplates=['<a href="#" onclick="return openLog(\'{{name}}\')">{{name}}</a>','{{size}}','{{modified}}' ];
let grid=ui.grid();
grid.box({
    classes:'r1 c1 h3 w3',
    url:'/api/Log',
    headers:headers,
    cellTemplates:cellTemplates
});

function openLog(filename){
    let mb=ui.modalBox({ title:filename, content:'Loading...' });
    new AjaxUtils.Request('/api/Log/name/'+filename,{
        method:'get',
        onSuccess:function (transport){
            mb.innerHTML="";
            let lines=transport.responseJSON.lines;
            lines.forEach(function(line){
                mb.style.fontSize="120%";
                line=line.replace("\\r","").replace("\\n","");
                if(0===line.indexOf("DEBUG")){
                    line='<span class="logdebug" style="opacity: 0.6">'+line+'</span>';
                } else if(0===line.indexOf("INFO")){
                    line='<span class="loginfo">'+line+'</span>';
                } else if(0===line.indexOf("WARN")){
                    line='<span class="logwarn" style="color:#c60;font-weight:bold">'+line+'</span>';
                } else if(0===line.indexOf("ERROR")){
                    line='<span class="logerror" style="color:red;font-weight:bold">'+line+'</span>';
                }
                mb.innerHTML+="<pre>"+line+"</pre>";
            });
            let header=mb.previousElementSibling;
            header.innerHTML+='&nbsp;&nbsp;&nbsp;&nbsp;Show:&nbsp;';
            header.innerHTML+='<label data-loglevel="debug"><input type="checkbox" />&nbsp;Debug</label>&nbsp;&nbsp;';
            header.innerHTML+='<label data-loglevel="info"><input type="checkbox" />&nbsp;Info</label>&nbsp;&nbsp;';
            header.innerHTML+='<label data-loglevel="warn"><input type="checkbox" />&nbsp;Warning</label>&nbsp;&nbsp;';
            header.innerHTML+='<label data-loglevel="error"><input type="checkbox" />&nbsp;Error</label>';
            header.querySelectorAll("label").forEach(function(lbl){
                lbl.style.display="inline-block";
                lbl.style.lineHeight="1.5em";
                lbl.querySelector("input").checked=true;
                lbl.querySelector("input").addEventListener("click",toggleLogLevel);
            });
        },
        onFailure:function (transport){
            mb.innerHTML=transport.responseText;
        },
    });
    return false;
}

function toggleLogLevel(evt){
    let lbl=evt.target.closest("label");
    let display=lbl.querySelector("input").checked ? "" : "none";
    let logLevel=lbl.dataset.loglevel;
    let mb=lbl.closest(".box").querySelector(".boxbody");
    mb.querySelectorAll(".log"+logLevel).forEach(function(line){
       line.style.display=display;
    });
}

</script><?php
include realpath(__DIR__) . '/../_common/footer.php';
