/**
 * /script/resulttest.js
 * @version 1.3
 * @desc Script file for the result viewer page
 * @author Fándly Gergő Zoltán (gergo@systemtest.tk, systemtest.tk)
 * @copy 2017 Fándly Gergő Zoltán
 * License:
    sQuiz for creating small jQuery based quizs in an implementable way
    Copyright (C) 2017  Fándly Gergő Zoltán

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

function showResSelector(){
    $("#menuwrapper").slideDown();
    $("#back").attr("onclick", "window.history.back()");
}

function resultFromFile(){
    $("#back").attr("onclick", "$(\"#resFromFile\").slideUp(); showResSelector()");
    $("#menuwrapper").slideUp();
    $("#resFromFile").slideDown();
}

function resultFromId(){
    $("#back").attr("onclick", "$(\"#resFromId\").slideUp(); showResSelector()");
    $("#menuwrapper").slideUp();
    $("#resFromId").slideDown();
}

function openResultFromFile(){
    var file=$("input[name=resfile]")[0].files[0];
    var fr=new FileReader();
    fr.onload=function(){
        openResultFromFileCallback(fr.result);
    };
    fr.readAsText(file, "utf-8");
    
    //hide solvedBy
    $("#quizDoneByHolder").css("display", "none");
}
function openResultFromFileCallback(file){
    showResults(file);
    $("#resFromFile").slideUp();
}

function openResultFromId(){
    $.ajax({
        url: "./engine/engine.php",
        type: "GET",
        data: {"getResult": $("input[name=testid]").val()},
        success: function(response){
            if(response!="not found"){
                response=(response instanceof Object)?response:JSON.parse(response);
                showResults(response.answered);
                
                //show solvedBy
                $("#quizDoneByHolder").css("display", "block");
                $("#quizDoneBy").html(response.submitter);
                
                //hide self
                $("#resFromId").slideUp();
            }
        }
    });
}

var chartCorrect=null;
var chartAnswers=null;
var chartTimeSpent=null;
var chartTimeSpentPie=null;
function showResults(results){
    //show back button
    $("#back").attr("onclick", "$(\"#analitycs\").slideUp(); showResSelector()");
    
    var res=(results instanceof Object)?results:JSON.parse(results);
    
    //process data
    var correct=0;
    var incorrect=0;
    var totalTime=0;
    var labels=[];
    var correctArr=[];
    var timeSpentArr=[];
    var colorArr=[];
    $.each(res.answers, function(key, val){
        if(val.correct){
            correct++;
        }
        else{
            incorrect++;
        }
        totalTime+=val.timeElapsed;
        labels.push((key+1).toString()+". "+lang.exercise);
        correctArr.push(val.correct);
        timeSpentArr.push(val.timeElapsed);
        colorArr.push("rgb("+(Math.floor(Math.random()*255)).toString()+", "+(Math.floor(Math.random()*255)).toString()+", "+(Math.floor(Math.random()*255)).toString()+")");
    });
    
    //set quiz datas
    $("#quizName").html(res.quizName);
    $("#quizDesc").html(res.quizDesc);
    var done=new Date(res.doneDate);
    $("#quizDone").html(done.getFullYear().toString()+"-"+(done.getMonth()+1).toString()+"-"+done.getDate().toString()+" "+done.getHours().toString()+":"+done.getMinutes().toString()+":"+done.getSeconds().toString());
    $("#quizTimeSpent").html(totalTime);
    
    //
    //show charts
    //
    
    //clear canvases
    if(chartCorrect!=null){
        chartCorrect.destroy();
        chartAnswers.destroy();
        chartTimeSpent.destroy();
        chartTimeSpentPie.destroy();
    }
    
    //chartCorrect
    chartCorrect=new Chart($("#chartCorrect"), {
        type: "pie",
        data: {
            labels: [lang.correct, lang.incorrect],
            datasets: [{
                label: lang.answers,
                backgroundColor: ["rgb(0, 255, 0)", "rgb(255, 0, 0)"],
                data: [correct, incorrect]
            }]
        },
        options: {
            responsive: false,
            title: {
                display: true,
                fontColor: "rgb(0, 0, 0)",
                text: lang.answers
            },
            legend: {
                labels: {
                    fontColor: "rgb(0, 0, 0)"
                },
                onClick: null
            }
        }
    });
    
    //chartAnswers
    chartAnswers=new Chart($("#chartAnswers"), {
        type: "bar",
        data: {
            labels: labels,
            datasets: [{
                label: lang.correct,
                backgroundColor: "rgba(34,168,186,0.9)",
                data: correctArr
            }]
        },
        options: {
            responsive: false,
            title: {
                display: true,
                fontColor: "rgb(0, 0, 0)",
                text: lang.correctAnswers
            },
            legend: {
                labels: {
                    fontColor: "rgb(0, 0, 0)"
                },
                onClick: null
            },
            scales: {
                xAxes: [{
                    gridLines: {
                        color: "rgb(0, 0, 0)"
                    },
                    ticks: {
                        fontColor: "rgb(0, 0, 0)"
                    }
                }],
                yAxes: [{
                    gridLines: {
                        color: "rgb(0, 0, 0)"
                    },
                    ticks: {
                        fontColor: "rgb(0, 0, 0)",
                        beginAtZero: true
                    }
                }]
            }
        }
    });
    
    //chartTimeSpent
    chartTimeSpent=new Chart($("#chartTimeSpent"), {
        type: "line",
        data: {
            labels: labels,
            datasets: [{
                label: lang.timeSpent,
                backgroundColor: "rgba(34,168,186,0.9)",
                data: timeSpentArr,
                lineTension: 0
            }]
        },
        options: {
            responsive: false,
            title: {
                display: true,
                fontColor: "rgb(0, 0, 0)",
                text: lang.timeSpent
            },
            legend: {
                labels: {
                    fontColor: "rgb(0, 0, 0)"
                },
                onClick: null
            },
            scales: {
                xAxes: [{
                    gridLines: {
                        color: "rgb(0, 0, 0)"
                    },
                    ticks: {
                        fontColor: "rgb(0, 0, 0)"
                    }
                }],
                yAxes: [{
                    gridLines: {
                        color: "rgb(0, 0, 0)"
                    },
                    ticks: {
                        fontColor: "rgb(0, 0, 0)",
                        beginAtZero: true
                    }
                }]
            }
        }
    });
    
    //chartTimeSpentPie
    chartTimeSpentPie=new Chart($("#chartTimeSpentPie"), {
        type: "pie",
        data: {
            labels: labels,
            datasets: [{
                label: lang.timeSpend,
                backgroundColor: colorArr,
                data: timeSpentArr
            }]
        },
        options: {
            responsive: false,
            title: {
                display: true,
                fontColor: "rgb(0, 0, 0)",
                text: lang.timeSpent
            },
            legend: {
                labels: {
                    fontColor: "rgb(0, 0, 0)"
                },
                onClick: null
            }
        }
    });
    
    //show container
    $("#analitycs").slideDown();
}
