<div class="panel-group" id="pluginOutputs">
    {% for test_code, poutput_list in grouped_plugin_outputs.items() %}
        <div id="header_{{ test_code }}"class="panel panel-default">
            <div class="panel-heading" style="padding: 0 15px">
                <div class="row">
                    <div class="col-md-10" style="padding-left: 15px">
                        <h4 class="panel-title">
                            <a data-toggle="collapse" data-parent="#pluginOutputs" href="#{{ test_code }}">
                                <h4 style="padding: 15px">{{ test_groups[test_code]['mapped_code'] }} {{ test_groups[test_code]['mapped_descrip'] }} <small>{{ test_groups[test_code]['hint'] }}</small></h4>
                            </a>
                        </h4>
                    </div>
                    <div class="col-md-2" style="text-align: center;">
                        <h4 id="header_badge_{{ test_code }}"></h4>
                    </div>
                </div>
            </div>
            <div id="{{ test_code }}" class="panel-collapse collapse">
                <div class="panel-body">
                    <ul class="nav nav-tabs">
                        <li class="brand disabled"><a class="btn" disabled="disabled">Type:</a></li>
                        {% set pactive = 'active' if len(poutput_list) == 1 else '' %}
                        {% for poutput in poutput_list %}
                        {% set pkey = poutput['plugin_type'] + '_' + poutput['plugin_code'] %}
                        <li class="{{ pactive }}">
                            <a id="tab_{{ pkey }}" href="#{{ poutput['plugin_group'] }}__{{ poutput['plugin_type'] }}__{{ test_code }}" data-toggle="tab">
                                {{ poutput['plugin_type'].replace('_',' ') }}
                            </a>
                        </li>
                        {% end %}
                        <li class="pull-right"><a href="{{ test_groups[test_code]['url'] }}" target="_blank" title="More information"><i class="fa fa-lightbulb-o"></i></a></li>
                    </ul>
                    <br />
                    <div class="tab-content">
                        {% for poutput in poutput_list %}
                        {% set pkey = poutput['plugin_type'] + '_' + poutput['plugin_code'] %}
                        <div class="tab-pane {{ pactive }}" id="{{ poutput['plugin_group'] }}__{{ poutput['plugin_type'] }}__{{ test_code }}">
                            <div class="pull-left" data-toggle="buttons-checkbox">
                                <blockquote><h4>{{ poutput['plugin_type'].replace('_',' ').capitalize() }}</h4><small>{{ poutput['plugin_code'] }}</small></blockquote>
                            </div>
                            <div class="pull-right" data-toggle="buttons">
                                {# TODO: Clean buttons code. #}
                                {% set user_rank = poutput['user_rank'] %}
                                {% if user_rank in [0, 1, 2, 3, 4, 5] %}
                                <label id="{{ pkey }}_0" class="btn rank {% if user_rank == 0 %}active{% end %}" title="Passing" data-code="{{ test_code }}"><input type="radio" id="0" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '0');"/><i class="fa fa-thumbs-up"></i></label>
                                <label id="{{ pkey }}_1" class="btn rank {% if user_rank == 1 %}active btn-success{% end %}" title="Informational" data-code="{{ test_code }}"><input type="radio" id="1" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '1');"/><i class="fa fa-info-circle"></i></label>
                                <label id="{{ pkey }}_2" class="btn rank {% if user_rank == 2 %}active btn-info{% end %}" title="Low" data-code="{{ test_code }}"><input type="radio" id="2" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '2');"/><i class="fa fa-exclamation-circle"></i></label>
                                <label id="{{ pkey }}_3" class="btn rank {% if user_rank == 3 %}active btn-warning{% end %}" title="Medium" data-code="{{ test_code }}"><input type="radio" id="3" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '3');"/><i class="fa fa-warning"></i></label>
                                <label id="{{ pkey }}_4" class="btn rank {% if user_rank == 4 %}active btn-danger{% end %}" title="High" data-code="{{ test_code }}"><input type="radio" id="4" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '4');"/><i class="fa fa-bell"></i></label>
                                <label id="{{ pkey }}_5" class="btn rank {% if user_rank == 5 %}active btn-critical{% end %}" title="Critical" data-code="{{ test_code }}"><input type="radio" id="5" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '5');"/><i class="fa fa-bomb"></i></label>
                                {% else %}
                                {% set owtf_rank = poutput['owtf_rank'] %}
                                <label id="{{ pkey }}_0" class="btn rank {% if user_rank == 0 %}active{% end %}" title="No ranking" data-code="{{ test_code }}"><input type="radio" id="0" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '0');"/><i class="fa fa-thumbs-up"></i></label>
                                <label id="{{ pkey }}_1" class="btn rank {% if owtf_rank == 1 %}active btn-success" style="opacity: 0.7{% end %}" title="Informational" data-code="{{ test_code }}"><input type="radio" id="1" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '1');"/><i class="fa fa-info-circle"></i></label>
                                <label id="{{ pkey }}_2" class="btn rank {% if owtf_rank == 2 %}active btn-info" style="opacity: 0.7{% end %}" title="Low" data-code="{{ test_code }}"><input type="radio" id="2" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '2');"/><i class="fa fa-exclamation-circle"></i></label>
                                <label id="{{ pkey }}_3" class="btn rank {% if owtf_rank == 3 %}active btn-warning" style="opacity: 0.7{% end %}" title="Medium" data-code="{{ test_code }}"><input type="radio" id="3" name="user_rank_button" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '3');"/><i class="fa fa-warning"></i></label>
                                <label id="{{ pkey }}_4" class="btn rank {% if owtf_rank == 4 %}active btn-danger" style="opacity: 0.7{% end %}" title="High" data-code="{{ test_code }}"><input type="radio" id="4" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '4');"/><i class="fa fa-bell"></i></label>
                                <label id="{{ pkey }}_5" class="btn rank {% if user_rank == 5 %}active btn-critical{% end %}" title="Critical" data-code="{{ test_code }}"><input type="radio" id="5" name="user_rank_button" onchange="updatePluginInfoAndPatch('{{ pkey }}', '{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', '5');"/><i class="fa fa-bomb"></i></label>
                                {% end %}
                            </div>
                            <br />
                            <br />
                            <br />
                            <br />
                            {# raw html[poutput["plugin_code"]] #}
                            <table class="table table-bordered table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th> RUNTIME </th>
                                        <th> TIME INTERVAL </th>
                                        <th> STATUS </th>
                                        {% if poutput['output_path'] %}
                                            <th> OUTPUT FILES </th>
                                        {% end %}
                                        <th> ACTIONS </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr
                                        {% if poutput['status'] == "Aborted" %}
                                        class="alert alert-warning"
                                        {% elif poutput['status'] == "Successful"%}
                                        class="alert alert-success"
                                        {% elif poutput['status'] == "Crashed" %}
                                        class="alert alert-error"
                                        {% elif poutput['status'] == "Running" %}
                                        class="alert alert-info"
                                        {% elif poutput['status'] == "Skipped" %}
                                        class="muted"
                                        {% else %}
                                        class=""
                                        {% end %}
                                    >
                                        <td> {{ poutput['run_time'] }} </td>
                                        <td> {{ poutput['start_time'] }} <br />{{ poutput['end_time'] }} </td>
                                        <td> {{ poutput['status'] }} </td>
                                        {% if poutput['output_path'] %}
                                            <td><a href="/output_files/{{ url_escape(poutput['output_path'], plus=False) }}/" target="_blank" class="btn btn-primary">Browse</a></td>
                                        {% end %}
                                        <td>
                                            <div class="btn-group">
                                                <button onclick="reRunPlugin('{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}');" class="btn btn-success" data-toggle="tooltip" data-placement="bottom" title="Rerun plugin">
                                                    <i class="fa fa-refresh"></i>
                                                </button>
                                                <button onclick="deletePluginOutput('{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}');" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Delete plugin output">
                                                    <i class="fa fa-times"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th colspan="6">
                                            <button class="btn btn-default pull-right" onclick="handleEditor('{{ poutput["plugin_group"] }}','{{ poutput["plugin_type"] }}','{{ test_code }}', this);"><i class="fa fa-pencil"></i> Notes</button>
                                        </th>
                                    </tr>
                                    <tr>
                                        <td colspan="6">
                                            <textarea class="editor" style="display: none;"></textarea>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th colspan="6">
                                            MORE DETAILS
                                        </th>
                                    </tr>
                                    <tr>
                                        <td colspan="6">
                                            {% raw poutput['output'] %}
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <a style="cursor:pointer" data-code="{{ test_code }}" class="lessbtn">Collapse</a>
                        </div>
                        {% end %}
                    </div>
                </div>
            </div>
        </div>
    {% end %}
</div>

<script>
/* Global copy of the plugins' outputs is built in the template itself to avoid
api calls. Only needed attributes are extracted
    + owtf_rank
    + user_rank
    + key
 */
var copyPOutputs = {};
{% for test_code, poutput_list in grouped_plugin_outputs.items() %}
    copyPOutputs['{{ test_code }}'] = {};
    {% for poutput in poutput_list %}
        copyPOutputs['{{ test_code }}']["{{ poutput['plugin_type'] }}"] = {
            {% if poutput['owtf_rank'] >= 0 %}
                "owtf_rank": {{ poutput['owtf_rank'] }},
            {% else %}
                "owtf_rank": null,
            {% end %}
            {% if poutput['user_rank'] >= 0 %}
                "user_rank": {{ poutput['user_rank'] }},
            {% else %}
                "user_rank": null,
            {% end %}
            "key": "{{ poutput['plugin_type'] }}@{{ poutput['plugin_code'] }}"
        };
    {% end %}
{% end %}

var pluginReportSpace = {
                    poutput_api_url:"{{ poutput_api_url }}",
                    transaction_log_url:"{{ transaction_log_url }}",
                    url_log_url:"{{ url_log_url }}"
                  };

function patchUserRank(group, type, code, user_rank){
    $.ajax({url:pluginReportSpace.poutput_api_url+group+'/'+type+'/'+code,
            type:'PATCH',
            data:{"user_rank":user_rank},
            error:function(xhr, textStatus, serverResponse){
                alertFail("Server replied: "+serverResponse);
                }
            });
    /* Update the user-local copy. */
    copyPOutputs[code][type].user_rank = user_rank;
}

function reRunPlugin(group, type, code) {
    //postToWorkList & updatePluginReport are obtained from target.html
    postToWorkList({"code":code, "group":group, "type":type}, true);
}

function deletePluginOutput(group, type, code){
    $.ajax({url:pluginReportSpace.poutput_api_url+group+'/'+type+'/'+code,
            type:'DELETE',
            success:function(){alertSuccess("Deleted plugin output for "+type+"@"+code); updatePluginReport();}, //updatePluginReport() is obtained from target.html
            error:function(xhr, textStatus, serverResponse){
                alertFail("Server replied: "+serverResponse);
                }
            });
}

function patchUserNotes(group, type, code, user_notes){
    $.ajax({url:pluginReportSpace.poutput_api_url+group+'/'+type+'/'+code,
            type:'PATCH',
            data:{"user_notes":user_notes},
            error:function(xhr, textStatus, serverResponse){
                alertFail("Server replied: "+serverResponse);
                }
            });
}

function handleEditor(group, type, code, instance){ // Same function called both to create or close editor
    var editorArea = $(instance).closest('table').find('.editor')
    try{
        var editor = editorArea.ckeditorGet(); // This line generates error if editor not found
        patchUserNotes(group, type, code, editorArea.val());
        editor.destroy();
        editorArea.css("display", "None");
    }catch(err){
        $.getJSON(pluginReportSpace.poutput_api_url+group+'/'+type+'/'+code, function(data){
                console.log(data);
                editorArea.val(data.user_notes);
                editorArea.ckeditor();
            });
    }
}

function navigateToTransaction(id){
    window.open(pluginReportSpace.transaction_log_url+id);
}

function resetPluginColors(id) {
    $("#" + id + "_0").removeClass("btn-passing");
    $("#" + id + "_1").removeClass("btn-success");
    $("#" + id + "_2").removeClass("btn-info");
    $("#" + id + "_3").removeClass("btn-warning");
    $("#" + id + "_4").removeClass("btn-danger");
    $("#" + id + "_5").removeClass("btn-critical");
    $("#tab_" + id).removeClass("alert-passing alert-success alert-info alert-warning alert-danger alert-critical");
};

function resetTestCaseColors(id) {
    $("#header_" + id).removeClass("panel-passing panel-success panel-info panel-warning panel-danger panel-critical");
}

function getAlertColor(level) {
    if (level == 0)
        return "passing";
    else if (level == 1)
        return "success";
    else if (level == 2)
        return "info";
    else if (level == 3)
        return "warning";
    else if (level == 4)
        return "danger";
    else if (level == 5)
        return "critical";
    return "";
}

function getLabelColor(level) {
    if (level == 0)
        return "<label class='alert alert-passing' style='margin-bottom: 0px'>Passing</label>";
    else if (level == 1)
        return "<label class='alert alert-success' style='margin-bottom: 0px'>Info</label>";
    else if (level == 2)
        return "<label class='alert alert-info' style='margin-bottom: 0px'>Low</label>";
    else if (level == 3)
        return "<label class='alert alert-warning' style='margin-bottom: 0px'>Medium</label>";
    else if (level == 4)
        return "<label class='alert alert-danger' style='margin-bottom: 0px'>High</label>";
    else if (level == 5)
        return "<label class='alert alert-critical' style='margin-bottom: 0px'>Critical</label>";
    return "";
}

/* Update the ranking value of a plugin button. */
function updatePluginInfoAndPatch(key, group, type, code, userRank) {
    $("#" + key + "_" + userRank).css("opacity", "");
    $("#tab_" + key).css("opacity", "");

    patchUserRank(group, type, code, userRank);
    updateTestCaseInfo(code);
    updateTargetInfo();
    updatePluginInfo(key, userRank);
};

/* Update the tab and buttons' colors of a plugin. */
function updatePluginInfo(key, userRank) {
    var id = $("#" + key + "_" + userRank);
    var tabID = $("#tab_" + key);
    var newClass = getAlertColor(userRank);

    resetPluginColors(key);

    $(id).toggleClass("btn-" + newClass);
    $(tabID).toggleClass("alert-" + newClass);
};

/* Update the header panel's color for one test case. */
function updateTestCaseInfo(code) {
    var testCaseMax = 0;
    var maxUserRank = -1;
    var maxOWTFRank = -1;
    $.each(copyPOutputs[code], function (type, poutput) {
        if (poutput.user_rank != null && poutput.user_rank != -1) {
            updatePluginInfo(poutput.key.replace('@', '_'), poutput.user_rank);
            if (poutput.user_rank > maxUserRank)
                maxUserRank = poutput.user_rank;
        }
        else if (poutput.owtf_rank != null && poutput.owtf_rank != -1) {
            updatePluginInfo(poutput.key.replace('@', '_'), poutput.owtf_rank);
            $("#tab_" + poutput.key.replace('@', '_')).css("opacity", "0.7");
            if (poutput.owtf_rank > maxOWTFRank)
                maxOWTFRank = poutput.owtf_rank;
        }
    });
    testCaseMax = (maxUserRank > maxOWTFRank) ? maxUserRank : maxOWTFRank;
    resetTestCaseColors(code);
    $("#header_" + code).toggleClass("panel-" + getAlertColor(testCaseMax));
    $("#header_badge_" + code).css("opacity", "");
    $("#header_badge_" + code).html('<i><small>' + getLabelColor(testCaseMax) + '</small></i>');
    if (testCaseMax > maxUserRank && testCaseMax != -1)
        $('#header_badge_' + code).css("opacity", "0.7");
}

/* Update the header panel's color of all test cases. */
function updateAllTestCasesInfo() {
    /* Find the current max for the test case. */
    $.each(copyPOutputs, function(code, types) {
        var testCaseMax = 0;
        var maxUserRank = -1;
        var maxOWTFRank = -1;
        $.each(types, function(type, poutput) {
            if (poutput.user_rank != null && poutput.user_rank != -1) {
                updatePluginInfo(poutput.key.replace('@', '_'), poutput.user_rank);
                if (poutput.user_rank > maxUserRank)
                    maxUserRank = poutput.user_rank;
            }
            else if (poutput.owtf_rank != null && poutput.owtf_rank != -1) {
                updatePluginInfo(poutput.key.replace('@', '_'), poutput.owtf_rank);
                $("#tab_" + poutput.key.replace('@', '_')).css("opacity", "0.7");
                if (poutput.owtf_rank > maxOWTFRank)
                    maxOWTFRank = poutput.owtf_rank;
            }
        });
        testCaseMax = (maxUserRank > maxOWTFRank) ? maxUserRank : maxOWTFRank;
        resetTestCaseColors(code);
        $("#header_" + code).toggleClass("panel-" + getAlertColor(testCaseMax));
        $("#header_badge_" + code).css("opacity", "");
        $("#header_badge_" + code).html('<i><small>' + getLabelColor(testCaseMax) + '</small></i>');
        if (testCaseMax > maxUserRank && testCaseMax != -1)
            $('#header_badge_' + code).css("opacity", "0.7");
    });
}

/* Update the page header's color of a target. */
function updateTargetInfo() {
    var localMax = 0;
    var maxUserRank = -1;
    var maxOWTFRank = -1;

    /* Find the current max for the target. */
    $.each(copyPOutputs, function(code, types) {
        $.each(types, function(type, poutput) {
            if (poutput.user_rank != null && poutput.user_rank > maxUserRank)
                maxUserRank = poutput.user_rank;
            else if (poutput.owtf_rank != null && poutput.owtf_rank > maxOWTFRank)
                maxOWTFRank = poutput.owtf_rank;
            if (maxUserRank == 5 || maxOWTFRank == 4)
                return false;
        });
        if (maxUserRank == 5 || maxOWTFRank == 4)
            return false;
    });
    localMax = (maxUserRank > maxOWTFRank) ? maxUserRank : maxOWTFRank;
    $('#rankingTargetInfo').css("opacity", "");
    $('#rankingTargetInfo').html('<i><small>' + getLabelColor(localMax) + '</small></i>');
    /* If the current max is given by OWTF, highlight it as such. */
    if (localMax > maxUserRank || localMax == -1)
        $('#rankingTargetInfo').css("opacity", "0.7");
}

/* On Ranking the plugin, it collapses the plugin */
function collapsePluginOnRank() {
    $('.btn.rank').click(function() {
        var id = $(this).attr('data-code');
        $('#' + id).removeClass('in');
    });
}

// Show less Functionality
function collapseOnShowLess() {
    $('.lessbtn').click(function() {
        var id = $(this).attr('data-code');
        $('#' + id).removeClass('in');
        $('html, body').animate({
            scrollTop: $("#header_" + id).offset().top
        }, 1000);
    });
}

$(function() {
    updateTargetInfo();
    updateAllTestCasesInfo();
    collapsePluginOnRank();
    collapseOnShowLess();
});
</script>
