// drag_one_item_per_category module

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

let setConfigHandler = new SetConfig();

let draggedItem = null;

let correctCount = 0;
let incorrectCount = 0;

let itemsDropped = 0;

let goToNextPage = false;
let nextPage;
let incorrectPage;
let itemsUsed = 0;
let allItems;

let autogenItemDiv = 0;

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

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

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

function correctChoice(isCorrect) {
    if (isCorrect) {
        correctCount++;
        $("#correct-count").html(correctCount);
        $("#dialog-box").addClass('correct').removeClass('incorrect') ;
        showDialog("That is correct.");
        audio.playAudioFile("../../audio/correct.wav") ;
    }
    else {
        incorrectCount++;
        $("#incorrect-count").html(incorrectCount);
        $("#dialog-box").addClass('incorrect').removeClass('correct') ;
        showDialog("That is incorrect.");
        audio.playAudioFile("../../audio/incorrect.wav") ;
    }
}

function showDialog(dialogText) {
    $("#dialog-text").html(dialogText);
    $("#dialog-frame").show();
    $("#dialog-box").show();
}

function testNumberCorrect() {
    // Test if player got enough correct to proceed
    // For now we just require all correct
    return (incorrectCount === 0);
}

function dialogOK(evt) {
    $("#dialog-box").hide();
    $("#dialog-frame").hide();
    if (goToNextPage) {
        if (testNumberCorrect()) {
            window.location.href = nextPage;
        }
        else {
            window.location.href = incorrectPage;
        }
    }
    if (itemsDropped >= maxItems) {
        $("#dialog-box").addClass('dialog-box-end').removeClass('correct incorrect') ;
        goToNextPage = true;
        showDialog(`<p>You got:<p/><p>Correct: ${correctCount}</p><p>Incorrect: ${incorrectCount}</p>`);
    }
}

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

    $(`#${draggedItem.itemDivID}`).remove();
    draggedItem = null;
    if (itemsUsed < maxItems) {
        addItem(allItems[itemsUsed]);
    }
}

function addItem(item) {
    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);

    itemsUsed++;
}

$(() => {

    $("#dialog-frame").hide();
    setConfigHandler.then((configuration)=>{
        let config = {...configuration}; // Shallow copy because configuration is const and we need to
                                         // add stuff.
        let itemsOnScreen = config.options.numberOfItemsOnScreen;
        options = config.options;
        $("#main").css("background-image", "url(" + config.options.page_background_image + ")");
        $("#instructionsText").html(options.instructionsPage1);
        allItems = (options?.randomizeItems) ? getShuffledArray(config.items) : config.items;
        maxItems = Math.min(config.options.numberOfAnswersRequired, allItems.length);

        config.categories = [
            {
                categoryID: "false",
                categoryTitle: "False",
            },
            {
                categoryID: "true",
                categoryTitle: "True",
            },
        ];

        $("#play").on("click",function() {
            $("#instructions1").remove();
            $(".category-div").removeClass('d-none');
            setupCategoryDisplay(config);
            setDropFunction(drop);

            let i;

            for (i = 0; i < itemsOnScreen; i++) {
                addItem(allItems[i]);
            }
            nextPage = options.completionURL;
            if (options.incorrectURL) {
                incorrectPage = options.incorrectURL;
            }
            else  {
                incorrectPage = nextPage ;
            }

            $("#instructions").html(options.instructions);
        });

    }) ;

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

export {setConfig};