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



let setConfigHandler = new SetConfig();
let allItems;
let draggedItem = null;
let draggedItemValue; // WILL HOLD CATEGORY (QUESTION) ID OF DRAGGED ITEM ;
let thisItem ;  // ID OF DIV BEING DRAGGED. DIV WILL BE DELETED WHEN DROPPED ;
let nextPage;
let goToNextPage = false;
let incorrectPage ; // Page to go to when incorrect ;
let correctCount = 0;
let incorrectCount = 0;
let itemsDropped = 0;
let itemsUsed = 0 ;
let autogenItemDiv = 0;
let answered ; // Blank answered ;
let maxItems ;

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

// VARIABLE AND FUNCTIONS TO HANDLE WHEN ITEM IS DRAGGED AND DROPPED ;
let $categoryDropArea = $(".blanks");
$categoryDropArea.on("dragover", dragover);
$categoryDropArea.on("drop", drop);
$categoryDropArea.on("dragenter", dragEnter);
$categoryDropArea.on("dragleave", dragLeave);
// Filled in on document.ready



function itemDragStart(evt) {
  draggedItem = evt.data;
  thisItem = "#" + draggedItem.itemDivID ;
  draggedItemValue = $(thisItem).attr("data-answer") ;
}

function dragover(evt) {
  evt.preventDefault();
}

// ON DROP, get data value of blank into which it was dropped ;
function drop(evt) {
  answered = $(evt.delegateTarget) ;
  itemsDropped++;
  let isCorrect = $(evt.delegateTarget).data("answer") === draggedItemValue ;

  correctChoice(isCorrect);

  $(thisItem).remove() ;
  doHighlight(answered, false);
}

function dragEnter(evt) {
  doHighlight($(evt.delegateTarget), true);
  evt.preventDefault();
}

function dragLeave(evt) {
  doHighlight($(evt.delegateTarget), false);
}

// highlights drop zone when item is over it ;
function doHighlight($element, highlightOn) {
  if (highlightOn) {
    $element.css("border", `2px gold solid`);
  }

}

/*  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();
}

/* 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);
    $(answered).text(draggedItem.item) ;
    $("#dialog-box").addClass('correct').removeClass('incorrect') ;
    showDialog("That is correct.");
    setAudioFile("../../audio/correct.wav") ;
    audio.play(true) ;
  }
  else {
    incorrectCount++;
    $("#incorrect-count").html(incorrectCount);
    $("#dialog-box").addClass('incorrect').removeClass('correct') ;
    showDialog("That is incorrect.");
    setAudioFile("../../audio/incorrect.wav") ;
    audio.play(true) ;
  }
}

/* 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-frame").addClass('d-none');


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

}

/* Creates and appends an item. It generates an itemID value, creates a div with that id, sets it to be draggable ,
    appends a title  to that div from the config file,
    when drag starts on the item, the itemDragStart function is executed
*/


$(() => {


  setConfigHandler.then((config)=>{
    let categories = config.categories;
    let options = config.options;
    let itemsOnScreen = config.options.numberOfItemsOnScreen;
    maxItems = config.options.numberOfAnswersRequired ;
    nextPage =  config.options.completionURL ;

    if (options.incorrectURL) {
      incorrectPage = options.incorrectURL;
    }
    else  {
      incorrectPage = nextPage ;
    }
    $("#instructions").html(config.options.instructions) ;
    if (options.instructions_audio) {

      setAudioFile(options.instructions_audio) ;
      $("#play-audio").removeClass('d-none').on("click",function(){
        audio.play(true) ;
      });
    }


    // CREATES A STATEMENT WITH A BLANK FOR AS MANY CATEGORIES AS EXIST IN THE CONFIG FILE ;
    for (let j = 0; j < (categories.length) ; j++) {
      let qdiv = "#" + "question" + (j) ;
      let qclass = "." + "question" + (j) ;
      $(qdiv).html(categories[(j)].categoryTitle) ;
      $(qclass).removeClass('d-none') ;
    }
    let i;
    allItems = (options?.randomizeItems) ? getShuffledArray(config.answers) : config.answers;
    function addItem(item, categoryID) {
      let itemDivID =  "itemID" + (autogenItemDiv++).toString();
      let $itemDiv = $("<div id='" + itemDivID + "' class= 'answers' draggable='true'  data-answer='" + categoryID + "'> </div>");
      $itemDiv.append($("<div class='item-caption'>" + item + "</div>"));
     $("#answers").append($itemDiv);
      $itemDiv.on("dragstart", {item, itemDivID}, itemDragStart);
      itemsUsed++;
    }
    setDropFunction(drop);
    for (i = 0; i < itemsOnScreen; i++) {
      addItem(config.answers[i].itemTitle, config.answers[i].categoryID);
    }
    $("#ok-button").on("click", dialogOK);
  });


});
export {setConfig};