<?php $nonce = wp_create_nonce( 'quttera' ); ?>

<script type="text/javascript">

    var last_log_line           = 0;
    var initial_load            = true;
    var log_lines               = Array();
    var max_log_lines           = 100;
    var logs_refresh_timer_set  = false;
    var status_reload_timer     = 0;
    var auto_refresh_enabled    = true;

    jQuery(document).ready(function($) {
        $.ajaxSetup({
            type: 'POST',
            async: true,
            url: ajaxurl,
            complete: function(xhr,status) {
                if ( status != 'success' ) {
                    console.log("Failed to communicate with WP for " + ajaxurl + " status " + status);
                }
            }
        });

        // Clear log button
        $('#clean-log').click( function() {
            if(confirm("Are you sure you want to clear the log?")) {
                QtrCleanExecutionLog();
            }
        });

        // Refresh button
        $('#refresh-log').click( function() {
            QtrReloadExecutionLog();
            QtrReloadLogStats();
        });

        // Export log button
        $('#export-log').click( function() {
            QtrExportLog();
        });

        // Initialize log display
        last_log_line = 0;
        QtrReloadExecutionLog();

        // Start auto-refresh timer
        if( auto_refresh_enabled ){
            status_reload_timer = setInterval( QtrAutoRefreshLog, 5000 );
        }
    });

    function QtrAutoRefreshLog(){
        if( auto_refresh_enabled ){
            QtrReloadExecutionLog();
        }
    }

    function QtrCleanExecutionLog( ){
        console.log("QtrCleanExecutionLog called");
        document.getElementById("log").value = "";
        last_log_line = 0;

        jQuery.ajax({
            data: {
                action: 'scanner-clean_log',
                _wpnonce: '<?php echo $nonce; ?>',
            }, 
            success: function(r) {
                console.log("Log cleared: " + r);
            }
        });
    }

    function QtrReloadExecutionLog ( ){
        console.log("QtrReloadExecutionLog called");
        jQuery.ajax({
            data: {
                action: 'scanner-get_log_lines',
                _wpnonce: '<?php echo $nonce; ?>',
                start_line: last_log_line,
            }, 
            success: function(r) {
                var log_lines_data = jQuery.parseJSON(r);
                if( !Array.isArray(log_lines_data) ){
                    console.log ("Invalid input: " + log_lines_data );
                    return;
                }

                if( log_lines_data ){
                    QtrLogMessages( log_lines_data );
                }
            }
        });
    }

    function QtrLogMessages( messages ){
        var body = "";
        for( var i =0; i < messages.length; i++ ){
            /* index 0 is line number, 1 is severity, 2 is message */
            var line = messages[i][1] + "\t" + messages[i][2] + "\n";
            if( log_lines.length >= max_log_lines ){
                log_lines.shift();
            }
            log_lines.push( line );
            body += line;
        }

        var logElement = document.getElementById("log");
        logElement.value = body;
        logElement.scrollTop = logElement.scrollHeight;
    }

    function QtrLogMessage(severity,message){
        if( !severity || !message ){
            return ;
        }

        var log_line = severity + "\t" + message;

        if( log_lines.length >= max_log_lines ){
            log_lines.shift();
        }

        log_lines.push( log_line );

        var body = "";
        for( var i = 0; i < log_lines.length; i++ ){
            body += log_lines[i] + "\n";
        }

        var logElement = document.getElementById("log");
        logElement.value = body;
        logElement.scrollTop = logElement.scrollHeight;
    }

    function QtrUpdateLogStats( counters ){
        var start = new Date( counters["START_TIME"] * 1000 );
        var ds = start.toDateString();
        var ts = start.toTimeString();
        
        document.getElementById("stat-scan-start-time").innerHTML = ds + " " + ts;
        document.getElementById("stat-total-scanned").innerHTML = counters["TOTAL"];
        document.getElementById("stat-clean-files").innerHTML = counters["CLEAN"];
        document.getElementById("stat-pot-suspicious").innerHTML = counters["POT_SUSPICIOUS"];
        document.getElementById("stat-suspicious").innerHTML = counters["SUSPICIOUS"];
        document.getElementById("stat-malicious").innerHTML = counters["MALICIOUS"];
    }

    function QtrExportLog(){
        var logContent = document.getElementById("log").value;
        
        if(!logContent){
            alert("Log is empty");
            return;
        }

        var element = document.createElement("a");
        element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(logContent));
        element.setAttribute("download", "quttera_scan_log_" + new Date().getTime() + ".txt");
        element.style.display = "none";
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }

</script>
