/**
 * Revised by annmaria on 1/13/25.
 */
import $ from "./jquery.module.js";
import SetConfig from "./set_config_class.js";
import {getMathProblemGenerator} from "./math_operation_problems.js";
import * as audio from "./audio.js";

let setConfigHandler = new SetConfig();
let config;

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

const correctClass = "correct-ttt";
const wrongClass = "wrong-ttt";

$(document).ready(async function(){
    const config = await setConfigHandler.getConfigAsync();
    const displayItems = config.displayItems;
    const options = config.options;

    let correctImage = null;
    let wrongImage = null;

    for (let item of displayItems) {
        switch(item.itemType) {
            case "wrong":
                wrongImage = {
                    src: item.itemImage,
                    alt: item.itemAltText
                };
                break;

            case "correct":
                correctImage = {
                    src: item.itemImage,
                    alt: item.itemAltText
                };
                break;
        }
    }

    // CREATE ARRAYS THAT WILL HOLD CORRECT ANSWERS, ALL SPAN ELEMENTS AND ALL INPUT ELEMENTS OF TYPE = TEXT ;
    let answers = [];
    let nc = 0, nw=0;

    let $spans = $("td span"); // CAN'T GET ALL SPAN ELEMENTS BECAUSE THAT WOULD INCLUDE POINTS AT THE BOTTOM ;
    // JUST GET SPAN ELEMENTS THAT ARE DESCENDANTS OF TABLE CELLS ;

    let inputs = document.querySelectorAll("input[type=number]") ;

    // let correctImages = [] ;
    // displayItems.forEach((x) => {if (x.itemType === "correct") {correctImages.push(x.itemImage);}});

    // WINNING COMBINATIONS IN TIC TAC TOE ;
    const winningCombinations =
        [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] ;

    let turns = 0 ; // Starts number of turns taken at 0 ;

    let $inputs = $("input[type=number]");

    $("#head2").css("background-image", `url(${options.backgroundImage.src})`);
    $("#head2").attr("title", options.backgroundImage.alt);
    $("#replay").on("click", () => {
        window.location.reload();
    });
    // SECTION TO CREATE PROBLEMS ;


    // Puts problem in each element of the array, generating random numbers between 2 and 12 ;
    let problemGenerator = getMathProblemGenerator({
        operator: "*",
        minValue: 2,
        maxValue: 12,
        template: "{1} X {2} ="
    });
    for (let index=0; index < $spans.length; ++index){
        let problem = problemGenerator.getProblem();
        $($spans[index]).text(problem);
        answers.push(problemGenerator.correctAnswer);
    }

    // IF THEIR ANSWER MATCHES CORRECT ANSWER IN ARRAY FOR THAT QUESTION, SHOW RABBIT ;
    // Different rabbits are shown based on question number ;
    // IF ANSWER IS WRONG EMPTY SNARE IS SHOWN ;
    // ADD CLASS OF RABBIT OR WRONG BASED ON ANSWER ;

   $('.b').on("click",function(){
       $(this).blur() ;
       let array_num = $(this).data("valp");
       let rightanswer = answers[array_num];
       let theiranswer = $(inputs[array_num]).val();
       let imageIdx = array_num % 3 ;
       turns = turns + 1 ;
       $("#q" + array_num).hide();

       const $img = $("#img" + array_num);
       if (rightanswer === theiranswer) {
            if (correctImage) {
                $img.attr(correctImage);
            }
           $img.show();

           $("#td" + array_num).addClass(correctClass);
           if ("goodSound" in options) {
               audio.playAudioFile(options.goodSound);
           }
           nc++;
       }
       else  {
           if (wrongImage) {
               $img.attr(wrongImage);
           }
           $img.show();
           $("#td"+ array_num).addClass(wrongClass)  ;
           if ("badSound" in options) {
               audio.playAudioFile(options.badSound);
           }
           nw++;
       }
       checkwin();
   });

    // CHECKS IF THE PLAYER HAS WON ;
    function checkwin() {
        if (turns < 3) {return false ; }
        let cells = $('td') ;
         cells = $.makeArray(cells);

        for (let a=0;  a < 8 ;a++ )
        {
            if ($(cells[winningCombinations[a][0]]).hasClass(correctClass) && $(cells[winningCombinations
                    [a][1]]).hasClass(correctClass) && $(cells[winningCombinations[a][2]]).hasClass(correctClass) )
            {
                $(".game_over").remove();
                $('#wongame').removeClass("d-none") ;
                $("#win-text").text(options.successText);
                $("#completion-url").attr("href", options.completionURL);
                $("#won-image").attr(options.winGameImage);
            }
            else if  ($(cells[winningCombinations[a][0]]).hasClass(wrongClass) && $(cells[winningCombinations[a][1]]).hasClass(wrongClass) && $(cells[winningCombinations[a][2]]).hasClass(wrongClass) )
            {
                $(".game_over").remove();
                $('#lostgame').removeClass("d-none") ;
                $("#lost-image").attr(options.loseGameImage);
            }
            else if (turns > 9) {
                $(".game_over").remove();
                $('#lostgame').removeClass("d-none") ;
                $("#lost-image").attr(options.loseGameImage);
            }

        }
    }
});

export {setConfig};
