import $ from "./jquery.module.js";
import SetConfig from "./set_config_class.js";
import * as audio from "./audio.js";

let setConfigHandler = new SetConfig();
let questionAnswered;
let correctAnswer;

function getCorrectAnswer() {
    return correctAnswer;
}

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

$.fn.show7gen = function() {
    this.removeClass("d-none");
    return this;
}

$.fn.hide7gen = function() {
    this.addClass("d-none");
    return this;
}

$(document).ready(async function(){
    let config_lib = await setConfigHandler.configPromise;
    let config = config_lib.config;
    let getProb = config_lib.getProb;

    let piece2; //moving this here so that if they get it wrong it will create a new question
    let words = "" ;

    //Creating variables. clicks recognizes whether it's been the first or second click.
    let playerPosition = "square105";
    let prevPosition = "square105";

    let ans_correct=0, ans_wrong=0;

    let firstRoll = true;
    let gender = "boy";
    let rows = 7;
    let columns = 15 ;
    let num_squares = rows*columns ;
    let moveto = 0 ;
    if (typeof (sessionStorage.getItem("points")) == 'undefined') {
        sessionStorage.setItem("points", "0");
    }
    let pts = sessionStorage.getItem("points");
    let gameCharacter = null;
    let squares = [];
    let $roll  = $("#roll");
    let $dice  = $("#dice");
    let $dice2 = $("#dice2");
    let $move  = $("#move");

    // let correctAnswer;
    let landed_text = [] ;
    $("#container").css('background-image',`url("${config.options.background_image}"`);

    function attachProblemButtons() {
        $("#getProblem").on("click", function () {
            $("#getProblem").hide7gen();
            correctAnswer = getProb("easy");
        });

        $("#getHardProblem").on("click", function () {
            $("#getHardProblem").hide7gen();
            correctAnswer = getProb("hard");
        });
    }

    // Initialize page elements
    $("#title-text").html(config.options.title);

    for (let character of config.characters) {
        $("#preface").append(`<img id="${character.id}" src="${character.image}" alt="${character.alt}">`);

        $(`#${character.id}`).on("click", function () {
            $("#preface").hide7gen();
            $("#instructionText").show7gen();
            $("#output").show7gen();
            gameCharacter = character;
            render();
            drawPiece(gameCharacter.piece_image,"square105");
        });
    }
    const $instructionText = $("#instructionText");

    for (const square of config.squares) {
        squares[square.square_type] = square;
        $instructionText.append(
            `<img class="game-icon" src="${square.image}" alt="${square.alt}" />`,
            square.instruction_text,
            "<br />");
        landed_text.push(square.landing_text);
    }
    $instructionText.append(`<br /> <img src="../../blocks/game_theme/theme/icons/next.png" alt="arrow" id="goArrow" />`)

    // START OF GAME ;
    setTimeout(function(){ $("#title").addClass('d-none'); ;
        setTimeout(function(){
            $("#instructionText").show7gen();
        },1500);
    }, 1500);

    $("#goArrow").on("click",function(){
        $instructionText.remove();
        $("#preface").show7gen();
    });


    //dice roll
    let rand;
    let doubleRoll = false;

    //add buttons functionality for instructions and hints.
    $roll.on("click", function () {
        rollDice();
    });

    function rollDice() {
        if (firstRoll) {
            firstRoll = false;
        }
        $dice.hide7gen();
        $("#correctDiv").hide7gen();
        $("#wrongDiv").hide7gen();
        $dice2.show7gen();

        rand = 1 + Math.floor(Math.random() * 6);
        $dice2.css("background-image", 'url("images/smalls/dice_' + rand + '.png")');
        if (doubleRoll) {
            rand = rand * 2;
            $("#dbl").show7gen();
            doubleRoll = false;
        }


        $roll.hide7gen();
        $move.show7gen();
        audio.playAudioFile(config.options.dice_roll_sound);
    }

    function removePiece(pos){
        $(`#player-piece`).remove()
    }

    // MOVE THE PLAYER ;
    function movePlayer() {
        // Get current position square ;
        prevPosition = playerPosition;
        // moveto = Number(prevPosition.substr(6)) - rand;
        moveto = Number(prevPosition.substring(6)) - rand;
        playerPosition =  "square" + moveto;
        let moveIndex = moveto - 1;

        removePiece(prevPosition)

        // FINDS ROW AND COLUMN OF NEW POSITION. LOOKS UP IN MAP WHAT IS IN THAT SPOT ;
        let thisrow = Math.trunc((moveIndex/columns ));
        let thiscolumn = (moveIndex % columns) ;
        piece2 = map[thisrow][thiscolumn] ;

        // WINNING THE GAME ;
        if (moveto <=  0) {
            playerPosition = "square1" ;
            pts = Number(pts) + 3;
            sessionStorage.setItem("points", pts);
            $("#next").on("click", function() {
                window.location.href = config.options.completionURL;
            })
            if (config.options.win_image.length > 0) {
                $("#container").css('background-image',`url("${config.options.win_image}"`);
            }
            setTimeout(function(){
                $(".game").remove() ;

                $("#title-text").text("You Won!");
                $("#title").removeClass('d-none');
                $("#next").removeClass('d-none');
            },900)
        }
        let pieceDrawn = gameCharacter.piece_image;
        drawPiece(pieceDrawn,playerPosition);
        words = landed_text[piece2];
        let soundForSquare = squares[piece2]?.sound ?? null;
        if (soundForSquare) {
            audio.playAudioFile(soundForSquare);
        }
        switch (piece2) {
            case 0:
                $dice.text(words);
                $roll.show7gen();
                $move.hide7gen();
                break;
            case 1:
               $dice.text(words);
                $roll.hide7gen();
                $move.hide7gen();
                $("#getProblem").show7gen();
                break;
            case 2:
                $dice.text(words);
                $("#advance").show7gen();
                $move.hide7gen();
                break;
            case 3:
                $dice.text(words);
                doubleRoll = true;
                $("#getHardProblem").show7gen(); // Testing. Add hard problem later ;
                $move.hide7gen();
                break;
            case 4:
                $dice.text(words);
                $move.hide7gen();
                setTimeout(function(){
                    rand = -15;
                    movePlayer();
                },3500);

                break;

        }
    }

    $move.on("click", function () {
        $("#dice2").hide7gen();
        $("#dbl").hide7gen();
        $("#dice").show7gen();
        movePlayer();
    });
    $("#advance").on("click", function () {
        rand = 15;
        $("#advance").hide7gen();
        $("#roll").show7gen();
        movePlayer();
    });

    attachProblemButtons();

    // ANSWER PROBLEMS ;


    // $("#answer").on("click", function () {
    //     let ans = Number($("#answerText").val());
    //     $("#problemArea").hide7gen();
    //     let correctAnswer = Number(getCorrectAnswer());
    //     doQuestionAnswered(correctAnswer === ans)
    // });

    questionAnswered = function (correct) {
        if (correct) {

            pts++;
            if (doubleRoll){
                pts++;
            }
            $("#correctDiv").text(config.options.correct_answer_text).show7gen();
            $("#roll").show7gen();
            $("#dice").text("");
            ans_correct++;

            sessionStorage.setItem("points", pts);
            $("#numberpts").text(pts);
        }
        else {
            $("#correctDiv").text(config.options.incorrect_answer_text).show7gen();
            doubleRoll = false;
            ans_wrong++;
            words = landed_text[piece2];
            let soundForSquare = squares[piece2]?.sound ?? null;
            if (soundForSquare) {
                audio.playAudioFile(soundForSquare);
            }
            switch(piece2) {
                case 1:
                    $("#dice").text(words);
                    $("#roll").hide7gen();
                    $("#move").hide7gen();
                    $("#getProblem").show7gen();
                    break;
                case 3:
                    $("#dice").text(words);
                    doubleRoll = true;
                    $("#getHardProblem").show7gen();
                    $("#move").hide7gen();
                    break;
            }
        }
        setTimeout(function(){
            $("#correctDiv").hide7gen();
            $("#output").show7gen();

        },2000);

    }

    let map = config.map;

    // THIS FUNCTION DRAWS THE GAME ;
    function render() {
        //Render the game by looping through the map arrays
        for (let row = 0; row < rows; row++) {
            for (let column = 0; column < columns; column++) {

                //Create a div tag called cell
                let cell = document.createElement("div");

                //Set its CSS class to "cell"
                cell.setAttribute("class", "cell");
                let thisid = column + 15*row + 1 ;
                //Set its name
                cell.setAttribute("name", thisid);

                //Set its id ;
                let idval = "square" + thisid ;
                cell.setAttribute("id", idval);

                let cellimg = document.createElement("img");

                stage.appendChild(cell);

                let sq = map[row][column];
                if (sq === 0 || !(sq in squares)) {
                    cellimg.src = config.options.blank_image;
                }
                else {
                        cellimg.src = squares[sq].image;
                }

                //Add the img tag to the <div id="square + thisid"> tag

                cell.appendChild(cellimg);
            }
        }
    }

    // DRAWS THE GAME PIECE ;

    function drawPiece(imgPiece,locPiece){
        $(`#${locPiece}`).append(`<img src="${imgPiece}" alt="${imgPiece}" id="player-piece">`);
    }


});

export {setConfig, questionAnswered, getCorrectAnswer};