
// drag_one_item_per_category module

import SetConfig from "./set_config_class.js";
import $ from "./jquery.module.js";
import * as audio from "./audio.js";
import {setupCategoryDisplay, itemsByCategory, setDropFunction} from "./drag_into_categories_utility.js";
import {setAudioFile} from "./audio.js";

let setConfigHandler = new SetConfig();
let draggedItem = null;
let correctCount = 0;
let incorrectCount = 0;

// Text shown when correct or incorrect ;
// Can be one of two languages as defined at bottom of screen ;
let correctText ;
let incorrectText ;
let endDialogpt1 ;
let endDialogpt2 ;

let itemsDropped = 0;

let goToNextPage = false;
let nextPage;
let incorrectPage ; // Page to go to when correct ;
let autogenItemDiv = 0;

// Filled in on document.ready
let options;
let maxItems;

let hintMessage ; // To be shown in dialog box when hint button clicked ;

let config_ui = null;

function setConfig(config) {
    setConfigHandler.setConfig(config);
}

function drop(evt, categoryID) {
    let isCorrect = draggedItem.item.categoryID === categoryID;
    correctChoice(isCorrect);
    itemsDropped++;

    $(`#${draggedItem.itemDivID}`).remove();
    draggedItem = null;
}

/* HANDLES WHAT HAPPENS AFTER THE ITEM IS DETERMINED CORRECT OR INCORRECT */
/* correctChoice - if the value passed to this function is correct then the number correct is incremented by 1,
 the number correct in the score box is shown as the new number and the dialog box shows a message "That is correct."
 If incorrect, the number incorrect is increased and the appropriate messages are shown.
 */
function correctChoice(isCorrect) {
    if (isCorrect) {
        correctCount++;
        $("#correct-count").html(correctCount);
        $("#dialog-box").addClass('correct').removeClass('incorrect') ;
        showDialog(correctText);
        setAudioFile("../../audio/correct.wav") ;
        audio.play(true) ;
    }
    else {
        incorrectCount++;
        $("#incorrect-count").html(incorrectCount);
        $("#dialog-box").addClass('incorrect').removeClass('correct') ;
        showDialog(incorrectText);
        setAudioFile("../../audio/incorrect.wav") ;
        audio.play(true) ;
    }
}

/*  SHOWS DIALOG BOX TELLING IF ANSWER WAS CORRECT OR INCORRECT */
function showDialog(dialogText) {
    $("#dialog-text").html(dialogText);
    $("#dialog-frame").removeClass('d-none') ;
    $("#dialog-box").show();
}

/* FUNCTION FOR OK BUTTON IN DIALOG BOX
   IF PLAYER HAS DROPPED REQUIRED NUMBER OF ITEMS, WILL SHOW NUMBER CORRECT AND INCORRECT'
      THEN CLOSE AND GO TO NEXT PAGE
      AS SPECIFIED IN THE COMPLETION URL IN THE CONFIG FILE
   OTHERWISE, IT JUST CLOSES THE BOX
 */
function dialogOK(evt) {
    $("#dialog-box").hide();
    $("#dialog-frame").addClass('d-none');
    if (goToNextPage) {
        if (config_ui && config_ui?.reloadWindowAtEnd) {
            window.location.reload();
        } else if (incorrectCount === 0) {
            goToCompletionPage(nextPage);
        }
        else {
            goToCompletionPage(incorrectPage);
        }
    }
    if (itemsDropped >= maxItems) {
        goToNextPage = true;
        showDialog(`<p>You got:<p/><p>Correct: ${correctCount}</p><p>Incorrect: ${incorrectCount}</p>`);
        $("#dialog-box").addClass('dialog-box-end').removeClass('correct incorrect') ;
    }
}

function goToCompletionPage(href) {
    if (options?.sendCompletionToParent) {
        parent.postMessage({
            action: "goto",
            destination: href
        });
    }
    else {
        window.location.href = href;
    }
}

function itemDragStart(evt) {
    draggedItem = evt.data;
}

$(() => {
    setConfigHandler.then((config) => {
        options = config.options;
        config_ui = config?.ui_params;

        $("#instructionsText").html(options.instructionsPage1);

        maxItems = config.categories.length;
        if (!options.instructionsPage1_audio) {
            $("#play-audio").hide();
        } else {
            setAudioFile(options.instructionsPage1_audio);
            $("#play-audio").on("click", function () {
                audio.play(true);
            });

            options = config.options;
            if (options.language2 === "Spanish") {
                incorrectText = 'Eso es incorrecto';
                correctText = 'Eso es correcto';
                endDialogpt1 = "Agarraste:<br/> Correcto: ";
                endDialogpt2 = "<br/>Incorrecto: ";
            } else {
                incorrectText = 'That is incorrect';
                correctText = 'That is correct';
                endDialogpt1 = "You got:<br/> Correct: ";
                endDialogpt2 = "<br/>Incorrect: ";
            }


            setupCategoryDisplay(config);
            setDropFunction(drop);

            // Get one random item of each category
            let catItems = itemsByCategory(config);
            let items = [];
            for (const catItem of catItems) {
                items.push(catItem[1][0]);
            }
            $("#play").on("click", function () {

                $("#instructions1").remove();
                audio.pause(true);

                if (options.instructions_audio) {
                    setAudioFile(options.instructions_audio);
                    $("#play-audio").on("click", function () {
                        audio.play(true);
                    }).show();
                }

                for (const item of items) {
                    let itemDivID = "itemDiv" in item ? item.itemDiv : "itemID" + (autogenItemDiv++).toString();

                    let $itemDiv = $(`<div id="${itemDivID}" class="${options.itemsClass}" draggable="true">
                              </div>`);

                    if ("image" in item) {
                        $itemDiv.append($(`<img src="${item.image}">`));
                    }
                    if ("itemTitle" in item) {
                        $itemDiv.append($(`<div class="item-caption">${item.itemTitle}</div>`));
                    }
                    $("#items").append($itemDiv);
                    $itemDiv.on("dragstart", {item, itemDivID}, itemDragStart);
                }
                nextPage = options.completionURL;
                if (options.incorrectURL) {
                    incorrectPage = options.incorrectURL;
                } else {
                    incorrectPage = nextPage;
                }
                if (options.hintMessage) {
                    hintMessage = options.hintMessage;
                    $("#hint").removeClass("d-none").on("click", function () {
                        $("#dialog-box").addClass('hint_box').removeClass('correct incorrect');
                        showDialog(hintMessage);
                    });
                }

                $("#instructions").html(options.instructions);
                $(".category-div").removeClass('d-none');
            });
        }
    });

    $("#ok-button").on("click", dialogOK);

});

export {setConfig};