
function HashTable() {
    let size = 0;
    let entry = new Object();
    this.add = function (key, value) {
        if (!this.containsKey(key)) {
            size++;
        }
        entry[key] = value;
    };
    this.getValue = function (key) {
        return this.containsKey(key) ? entry[key] : null;
    };
    this.remove = function (key) {
        if (this.containsKey(key) && (delete entry[key])) {
            size--;
        }
    };
    this.containsKey = function (key) {
        return (key in entry);
    };
    this.containsValue = function (value) {
        for (var prop in entry) {
            if (entry[prop] == value) {
                return true;
            }
        }
        return false;
    };
    this.getValues = function () {
        var values = new Array();
        for (var prop in entry) {
            values.push(entry[prop]);
        }
        return values;
    };
    this.getKeys = function () {
        var keys = new Array();
        for (var prop in entry) {
            keys.push(prop);
        }
        return keys;
    };
    this.getSize = function () {
        return size;
    };
    this.clear = function () {
        size = 0;
        entry = new Object();
    }
}

let      myuser;
let      lines;
let      routineTab     = new HashTable();
let      vulTypeCount   = new HashTable();
let      fileCount      = new HashTable();

$(document).ready(function () {
    let outhtml;
    try {
        outhtml = $(window.frames["opencc_vul"].document).html();
    }catch (e) {
        outhtml = $(window.frames["opencc_vul"].document)[0].body.innerHTML
    }
    if(outhtml  ===  "" || outhtml == undefined || outhtml == null || outhtml.length == 0){
        $.ajax({url: "opencc_vul.txt"}).done(display_content);
    } else {
        display_content(outhtml);
    }
});

function display_content(s){
    let    answer         = s;
    let    i              = 0;
    let    count          = 0;
    let    one_obj        = {};
    let    obj_list       = [];
    let    all_lines      = "";

    lines     = answer.split("\n");

    for(i = 0; i < lines.length ; i++){

        let n = lines[i].match(/[a-zA-Z\._:0-9]+/g);

        if(n != null) {

            let res        = {};                        // One line of result
            res.filename   = n[0];
            res.vultype    = n[4];
            res.variate    = n[8];
            res.subroutine = n[9];
            res.lineno     = n[1];

            if(!routineTab.containsKey
            (res.subroutine+"+"+res.variate+"+"+res.filename))
            {
                //  Repetition Check Passes
                routineTab.add(res.subroutine+"+"+res.variate+"+"+res.filename, res.vultype);
                obj_list.push(res);
                all_lines += `L ${res.lineno} - <span> ${res.filename}</span>  <br>`;
                count ++;
                if(vulTypeCount.containsKey(res.vultype)){
                    let vul_list  =  vulTypeCount.getValue(res.vultype);
                    vul_list.push(res);
                }else{
                    let vul_list  =  new Array();
                    vul_list.push(res);
                    vulTypeCount.add(res.vultype, vul_list);
                }

                if(fileCount.containsKey(res.filename)){
                    let vul_list  =  fileCount.getValue(res.filename);
                    vul_list.push(res);
                }else{
                    let vul_list  =  new Array();
                    vul_list.push(res);
                    fileCount.add(res.filename, vul_list);
                }
            }
        }
    }
    showToPage();
}

function showToPage() {
    let s    = "";
    let keys = fileCount.getKeys();
    let one  = [];
    let doms = "";
    for (i = 0; i<fileCount.getSize(); i++){
        one   = fileCount.getValue(keys[i]);
        doms += makeOneFile(keys[i], one.length);
    }
    $("#perfile").html(doms);
    let bug_count = routineTab.getSize();
    $("#risk-counter").text(bug_count);
    $("#risky-f-counter").text(fileCount.getSize());
    $("#f-counter").text(131);
    $("#time-counter").text(21);
    showFiles();
    showVul();
}

function makeOneFile(file_name, file_count) {
    return `<li class="list-group-item btn btn-outline-primary d-flex justify-content-between align-items-center"  onclick='showDetial("${file_name}")' >
               ${file_name}
               <span class="badge badge-primary badge-pill">${file_count}</span>
            </li>`;
}


function showVul() {
    let vul_data  = [];
    let i         = 0;
    let keys      = vulTypeCount.getKeys();
    for(i = 0 ; i < vulTypeCount.getSize(); i++){
        vul_data.push({name: keys[i], y:vulTypeCount.getValue(keys[i]).length});
    }

    Highcharts.chart('container1', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Vulnerabilities Per Category'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        },
        series: [{
            name: 'Category',
            colorByPoint: true,
            data: vul_data
        }]
    });
}

function showFiles() {

    let vul_file  = [];
    let vul_count = [];
    let i         = 0;
    let keys      = fileCount.getKeys();
    for(i = 0 ; i < fileCount.getSize(); i++){
        vul_file.push(keys[i]);
        vul_count.push(fileCount.getValue(keys[i]).length);
    }

    var chart = Highcharts.chart('container2', {
        chart: {
            zoomType: 'xy'
        },
        title: {
            text: 'Vulnerabilities Per File '
        },
        subtitle: {
            text: ' AliOS-Things '
        },
        xAxis: [{
            categories: vul_file,
            crosshair: true
        }],
        yAxis: [{ // Primary yAxis
            labels: {
                format: '{value} risks',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            title: {
                text: 'Count',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            }
        }],
        tooltip: {
            shared: true
        },
        // legend: {
        //     layout: 'vertical',
        //     align: 'left',
        //     verticalAlign: 'top',
        //     y: 100,
        //     floating: true,
        //     backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
        // },
        series: [{
            name: 'Per File',
            type: 'column',  /**spline */
            data: vul_count,
            tooltip: {
                valueSuffix: ' risks'
            }
        }]
    });
}



function showDetial(file_name){
    let vul      =  fileCount.getValue(file_name);
    let all_html =  "";
    $("#modal-title").text(file_name + " Detail");
    for(i= 0 ; i < vul.length; i ++){
        all_html += ` In function ${vul[i].subroutine},<br> Line ${vul[i].lineno}, &nbsp;&nbsp;&nbsp;  
                       <span style="color:red"> ${vul[i].variate} </span> - 
                      <span style="color:orange"> ${trans(vul[i].vultype)}</span> <br><br> `;
    }
    $("#file-detial").html(all_html);
    $("#modal-detial").modal('show');
}

function trans(tp){
    if(tp == "NPD"){
        return "Null Pointer Dereference";
    }else if(tp == "UIV"){
        return "Uninitialized Variable";
    }
}