<!doctype html>
<html lang="en">
<head>
<title>Tim's Language Helper: word test</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style>
    table.meaning, td.meaning {
        border: none;
        border-collapse: collapse;
    }
   
    p.debug {
        display: none;
    }
    td.correct_answer {
        display: none;
    }
    td.wrong_answer {
        display: none;
        background-color: red;
        color: white;
        border: 1px solid red;
        border-radius: 5px;
        align-content: center;
    }
    div.word_area {
        padding: 10px;
        color: blue;
        font-size: 150%;
    }
    table.test_area {
        margin-left: 10%;
    }
    div.results_area {
        display:none;
    }
    table.results_table, td.result_word, td.result_meaning, td.result_errors {
        border: 1px dotted blue;
        border-collapse: collapse;
        margin-left: 10%;
        padding: 5px;
    }
    td.result_word_hdr, td.result_meaning_hdr, td.result_errors_hdr {
        border: 1px dotted blue;
        border-collapse: collapse;
        margin-left: 10%;
        padding: 5px;
        font-weight: bold;
    }

</style>
<script>
    class Result {
      constructor(word, correct_answers) {
        this.word = word
        this.correct_answers = correct_answers
        this.error_count = 0
      }
    }

    // global variables
    let g_words = null
    let g_word_no = 0
    let g_from_language = null
    let g_to_language = null
    let g_words_num
    let g_correct_answers = 0
    let g_correctly_answered = 0
    let g_total_errors = 0
    let g_result = null

    // copied from web...
    function shuffle(array) {
      let currentIndex = array.length,  randomIndex;
    
      // While there remain elements to shuffle.
      while (currentIndex > 0) {
    
        // Pick a remaining element.
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
    
        // And swap it with the current element.
        [array[currentIndex], array[randomIndex]] = [
          array[randomIndex], array[currentIndex]];
      }
    
      return array;
    }
    
    function addAnswer(answer) {
        //alert(answer.word + ": " + answer.type)
        table = document.getElementById("test_area")
        var row = document.createElement("tr")
        var cell = document.createElement("td")
        var btn = document.createElement("button")
        btn.innerHTML = "?"
        btn.id = "btn_" + answer.type + "_" + answer.meaning_id
        btn.addEventListener("click", answer_clicked)
        cell.appendChild(btn)
        row.appendChild(cell)
        
        cell = document.createElement("td")
        cell.className = "answer_word"
        cell.innerHTML = answer.word
        row.appendChild(cell)
        
        cell = document.createElement("td")
        cell.id = "result_" + answer.type + "_" + answer.meaning_id
        if (answer.type == "correct") {
            cell.className = "correct_answer"
            cell.innerHTML = "&#x2705;" // tick
        } else {
            cell.className = "wrong_answer"
            cell.innerHTML = "&nbsp;&#215;"
        }
        row.appendChild(cell)

        table.appendChild(row)
    }

    function answer_clicked(event) {
        var btn = event.target.id
        var x = btn.indexOf("_")
        var result_id = "result" + btn.substr(x)
        document.getElementById(result_id).style.display = "block"
        // record error or success on database
        var bits = btn.split("_")
        if (bits[1] == "correct") {
            add_word_test_stat(bits[2])
            // see if all correct answers given yet
            if (++g_correctly_answered == g_correct_answers) {
                add_result_row()
                if (++g_word_no < g_words.length) {
                    get_word_test(g_word_no)
                } else { // words finished
                    reveal_results()
                }
            } else {
                var instructions = document.getElementById("instructions").innerHTML
                document.getElementById("instructions").innerHTML = instructions + "<br/>Well done! More to find..."
            }
        } else {
            add_word_test_error(bits[2], g_words[g_word_no].word_id)
            g_result.error_count++
            g_total_errors++
        }
        // hide button after use
        document.getElementById(btn).style.display = "none"
    }
    
    // reveal results
    function reveal_results() {
        document.getElementById("instructions").style.display = "none"
        document.getElementById("word").style.display = "none"
        document.getElementById("test_area").style.display = "none"
        document.getElementById("results_area").style.display = "block"
    }
    
    // AJAX request to add a word test error to database
    function add_word_test_error(meaning_id, wrong_word_id) {
        user_id = 1
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            //document.getElementById("result").innerHTML = this.responseText;
        }
        request = "add_word_test_error.php?user_id=" + user_id + "&meaning_id=" + meaning_id + "&wrong_word_id=" + wrong_word_id
        xhttp.open("GET", request, true);
        xhttp.send();
    }
    
    // AJAX request to add a successful word test statistic to database
    function add_word_test_stat(meaning_id) {
        user_id = 1
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
        }
        request = "add_word_test_stat.php?user_id=" + user_id + "&meaning_id=" + meaning_id
        xhttp.open("GET", request, true);
        xhttp.send();
    }

    // Add row to result table (only visible after tests completed)
    function add_result_row() {
        var result_table = document.getElementById("results")
        var row = document.createElement("tr")
        var cell = document.createElement("td")
        cell.className = "result_word"
        cell.innerHTML = g_result.word
        row.appendChild(cell)
        cell = document.createElement("td")
        cell.className = "result_meaning"
        var new_line = ""
        for (var i = 0; i < g_result.correct_answers.length; i++) {
            cell.innerHTML += new_line + g_result.correct_answers[i].word
            new_line = "<br/>"
        }
        row.appendChild(cell)
        cell = document.createElement("td")
        cell.className = "result_errors"
        cell.innerHTML = g_result.error_count
        row.appendChild(cell)
        result_table.appendChild(row)
    }

    // Add header row to result table (only visible after tests completed)
    function add_result_header() {
        var result_table = document.getElementById("results")
        var row = document.createElement("tr")
        var cell = document.createElement("td")
        cell.className = "result_word_hdr"
        cell.innerHTML = "Word"
        row.appendChild(cell)
        cell = document.createElement("td")
        cell.className = "result_meaning_hdr"
        cell.innerHTML = "Meaning(s)"
        row.appendChild(cell)
        cell = document.createElement("td")
        cell.className = "result_errors_hdr"
        cell.innerHTML = "Errors"
        row.appendChild(cell)
        result_table.appendChild(row)
    }

    // AJAX request to get a word test
    function get_word_test(word_no) {
        word = g_words[word_no]
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            //document.getElementById("debug").innerHTML = this.responseText
            document.getElementById("word").innerHTML = word.word;
            var test_json = JSON.parse(this.responseText)

            var correct_answers = test_json.correct_meanings
            var incorrect_answers = test_json.incorrect_meanings
            var random_answers = test_json.random_meanings
            var total = random_answers.length + incorrect_answers.length + correct_answers.length
            // store number of correct answers in global variable
            g_correct_answers = correct_answers.length
            // initialise result in global variable
            g_result = new Result(word.word, correct_answers)
            
            // initial instructions
            var instructions = "Click button to reveal whether the relevant word is correct meaning."
            if (g_correct_answers > 1) {
                instructions += "<br/>There are " + g_correct_answers + " correct_answers..."
            } else {
                instructions += "<br/>There is 1 correct_answer..."
            }
            document.getElementById("instructions").innerHTML = instructions
            // create array of all answers
            answers = new Array()
            for (var i = 0; i < correct_answers.length; i++) {
                answers.push(correct_answers[i])
            }
            for (var i = 0; i < incorrect_answers.length; i++) {
                answers.push(incorrect_answers[i])
            }
            for (var i = 0; i < random_answers.length; i++) {
                answers.push(random_answers[i])
            }
            document.getElementById("instructions").style.display = "block"
            document.getElementById("word").style.display = "block"
            //clear display table and load answers to test area in random order
            document.getElementById("test_area").innerHTML = ""
            shuffle(answers)
            answers.forEach(addAnswer)
            // reset correct answers checks
            g_correctly_answered = 0
        }
        request = "get_word_test.php?word_id=" + word.word_id
        xhttp.open("GET", request, true);
        xhttp.send();
    }
    
    // AJAX request to get all words to be tested
    function get_words_for_test() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            var test_json = JSON.parse(this.responseText)
            g_words = test_json.words
            // display test for first word
            g_word_no = 0
            get_word_test(g_word_no)
        }
        var slt_frm = document.getElementById("slt_from_language")
        g_from_language = slt_frm.options[slt_frm.options.selectedIndex].value
        var slt_to = document.getElementById("slt_to_language")
        g_to_language = slt_to.options[slt_to.options.selectedIndex].value
        var slt_num = document.getElementById("slt_words_in_test")
        g_word_num = slt_num.options[slt_num.options.selectedIndex].value
        request = "get_words_for_test.php?language=" + g_from_language + "&limit=" + g_word_num
        xhttp.open("GET", request, true);
        xhttp.send();
        // reset results
        document.getElementById("results_area").style.display = "none"
        document.getElementById("results").innerHTML = ""
        // set up results table headers
        add_result_header()
        // initialise test area
        document.getElementById("test_area").innerHTML = ""
        document.getElementById("test_area").style.display = "block"
    }

</script>
</head>
<body>

<h1>Tim's Language Helper</h1>
<h2>Word Test</h2>
<br/>From language:
<select id="slt_from_language">
    <option value="1">English</option>
    <option value="2">Greek</option>
</select>
<br/>To language:
<select id="slt_to_language">
    <option value="1">English</option>
    <option value="2">Greek</option>
</select>
<br/>Number of words in test:
<select id="slt_words_in_test">
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="30">30</option>
    <option value="40">40</option>
    <option value="50">50</option>
</select>
<br/><button onclick="get_words_for_test()">Start Test</button>
<div id="debug"></div>
<div id="instructions" class="instructions_area"></div>
<div id="word" class="word_area"></div>
<table id="test_area" class="test_area"></table>
<div id="results_area" class="results_area">
    <p>Review your results:</p>
    <table id="results" class="results_table">
    </table>
</div>

</body>
</html>