import $ from "./jquery.module.js";
import SetConfig from "./set_config_class.js";
import * as dialog from "./dialog.js";
import {getShuffledArray} from "./random.js";

let setConfigHandler = new SetConfig();

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

$(async function () {

    let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z'];

    let word ;              // Selected word
    let guess ;             
    let guesses = [ ];      // Stored guesses
    let chances ;             // chances
    let counter ;           // Count correct guesses
    let space;              // Number of spaces in word '-'
    let list;
    let context;
    let currentWordIdx = 0;

    // Get elements
    let showchances = document.getElementById("mychances");
    let showClue = document.getElementById("clue");


    let config = await setConfigHandler.configPromise;

    let words = config.options.randomizeWords ? getShuffledArray(config.words) : config.words;

    $(".end-buttons").hide();

    $("#play-again").on("click", ()=>  window.location.reload());
    $("#continue").on("click", () => window.location.href = config.options.completionURL);

    // create alphabet ul
    function buttons () {
        let myButtons = document.getElementById('buttons');
        let letters = document.createElement('ul');

        for (let i = 0; i < alphabet.length; i++) {
            letters.id = 'alphabet';
            list = document.createElement('li');
            list.id = 'letter';
            list.innerHTML = alphabet[i];
            check();
            myButtons.appendChild(letters);
            letters.appendChild(list);
        }
    }

    function setTopic() {
        let topic = words[currentWordIdx]?.topic;
        clue.innerHTML = topic ? `Topic: ${topic}` : ``;
    }

    // Create guesses ul ;
    function result() {
        let wordHolder = document.getElementById('hold');
        let correct = document.createElement('ul');

        for (let i = 0; i < word.length; i++) {
            correct.setAttribute('id', 'my-word');
            guess = document.createElement('li');
            guess.setAttribute('class', 'guess');
            if (word[i] === "-") {
                guess.innerHTML = "-";
                space = 1;
            } else {
                guess.innerHTML = "_";
            }

            guesses.push(guess);
            wordHolder.appendChild(correct);
            correct.appendChild(guess);
        }
    }

    // Show chances
    async function comments() {
        showchances.innerHTML = "You have " + chances + " chances";
        if (chances < 1) {
            showchances.innerHTML = "Game Over";
            $("#alphabet").hide();
            $("#clue").hide();
            $("#play-again").show();
            $("#continue").show();
          // window.location.href="lost.html";
        }
        if (counter + space === guesses.length) {
            let choice = await dialog.showChoiceDialogAsync(
                "Congratulations! Do you want to play another game?",
                ["Play Again", "Continue"]);
            switch(choice) {
                case "Play Again":
                    window.location.reload();
                    break;

                case "Continue":
                    window.location.href = config.options.completionURL;
                    break;
            }
        }
    }

    function advanceHangmanImage() {
        const hangman = config.hangman[chances];
        const src = hangman.imagePath;
        const alt = hangman.altText;
        $("#stickman-image").attr({src, alt});
    }


    //
    // OnClick Function
    function check() {
        list.onclick = function () {
            let guess = (this.innerHTML);
            this.setAttribute("class", "active");
            this.onclick = null;
            this.innerHTML = "";
            for (let i = 0; i < word.length; i++) {
                if (word[i] === guess) {
                    guesses[i].innerHTML = guess;
                    counter += 1;
                }
            }
            let j = (word.indexOf(guess));
            if (j === -1) {
                chances -= 1;
                comments();
                advanceHangmanImage();
            } else {
                comments();
            }
        }
    }


    // Play
    function play() {
        word = words[currentWordIdx].word;
        word = word.replace(/\s/g, "-");
        buttons();

        guesses = [ ];
        // chances = 10;
        chances = config.hangman.length;
        counter = 0;
        space = 0;
        result();
        comments();
        setTopic();
    }

    play();

    // Hint
$("#hint").on("click",function(){
    showClue.innerHTML = `Hint: - ${words[currentWordIdx].hint}`;
    $("#hint").fadeOut("slow");
    $("#instruct").text("Click a letter");
});


    // Reset

    document.getElementById('play-again').addEventListener("click", function() {
    correct.parentNode.removeChild(correct);
        letters.parentNode.removeChild(letters);
        showClue.innerHTML = "";
        context.clearRect(0, 0, 400, 400);
        play();
    });
});

export {setConfig};