// 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";
import {setAudioFile} from "./audio.js";

let setConfigHandler = new SetConfig();

let draggedItem = null;

let correctCount = 0;
let incorrectCount = 0;

let itemsDropped = 0;

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

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

let correctText ;
let incorrectText ;
let endDialogpt1 ;
let endDialogpt2 ;

// Filled in on document.ready
let options;
let maxItems; // NUMBER OF ANSWERS REQUIRED - from config file;

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

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

/* 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 hint_box') ;
        showDialog(correctText);
        setAudioFile("../../audio/correct.wav") ;
        audio.play(true) ;
    }
    else {
        incorrectCount++;
        $("#incorrect-count").html(incorrectCount);
        $("#dialog-box").addClass('incorrect').removeClass('correct hint_box') ;
        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").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 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").hide();
    if (goToNextPage) {
        if (testNumberCorrect()) {
            window.location.href = nextPage;
        }
        else {
            window.location.href = incorrectPage;
        }
    }
    if (itemsDropped >= maxItems) {
        goToNextPage = true;
        $("#dialog-box").addClass('dialog-box-end').removeClass('correct incorrect') ;

        showDialog( endDialogpt1 + correctCount + endDialogpt2 + incorrectCount );
    }
}

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

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

/* Creates and appends an item. It generates an itemID value, creates a div with that id, sets it to be draggable ,
 appends a title and image to that div from the config file,
 when drag starts on the item, the itemDragStart function is executed
 */
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((config)=>{
        let itemsOnScreen = config.options.numberOfItemsOnScreen;

          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: " ;
        }

        setAudioFile(options.instructionsPage1_audio) ;
          $("#play-audio").on("click",function(){
              audio.play(true) ;
          });
        allItems = (options?.randomizeItems) ? getShuffledArray(config.items) : config.items;
        maxItems = Math.min(config.options.numberOfAnswersRequired, allItems.length);

        $("#instructionsText").html(options.instructionsPage1);
        console.log(options.language2) ;

        $("#play").on("click",function(){
            audio.pause(true) ;
            setAudioFile(options.instructions_audio) ;
            $("#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 ;
            }
            hintMessage = options.hintMessage ;
            if (hintMessage.length > 0) {
                $("#hint").removeClass("d-none").on("click",function(){
                    $("#dialog-box").addClass('hint_box').removeClass('correct incorrect') ;
                    showDialog(hintMessage) ;
                }) ;

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

        });
    });

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

export {setConfig};