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

let setConfigHandler = new SetConfig();
let config;
let gameWon = false;

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

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

$(async function() {

    config = await setConfigHandler.getConfigAsync();

    if (config.options.backgroundImage) {
        $("#container").css("background", `url(${config.options.backgroundImage})`);
    }

    if (config.options.introduction) {
        $("#intro-banner").html(config.options.introduction);
    }

    $("#continue-button").on("click", () => {
        window.location.href = config.options.completionURL;
    });

    //Timer script ;
    let time = config.options.timeLimitInSeconds;
    let timesUp = 0;
    let timer;

    function countDown() {
        if (time > 0) {
            $("#timer").text(time);
            time = time - 1;
        }
        else if (time === 0) {
            clearInterval(timer)
            if (!gameWon) {
                $("#timer").text(0);
                timesUp = 1;
                audio.pause();
                $(".game").hide();
                $("#lost").show();
            }
        }
    }


//<!--END OF TIMER SCRIPT-->

// Section to include sound. ;

    let matched;
    let startTime;
    let count = 0;
    let deckSize = config.options.numberOfPairsDisplayed;
    let lock = false // Used to disallow clicking on 3 cards ;
    let chosen = null;
    const back = config.options.cardBackImage;
    const blank = config.options.blankCardImage;

    let deck = []

    function stack_cards() {
        let shuffledCards = getShuffledArray(config.cardPairs);
        for (let i=0; i < deckSize; i++) {
            let pair = shuffledCards[i];
            let firstCardInPair = [pair[0], i]
            let secondCardInPair = [pair[1],i]

            deck.push(firstCardInPair, secondCardInPair);
        }

        make_deck()
    }

    function make_deck(){
        let $canvas = $("#canvas");
        shuffle(deck);
        let bucket = $("<div class='bucket'>");
        for (let i=0; i < deckSize*2; i++) {
            if(i === deckSize){
                $canvas.append(bucket);
                bucket = $("<div class='bucket'>");
            }
            let card = $("<img class='card'/>");
            let current = deck[i];
            $(card).attr({src: back, "data-src": current[0], "data-val": current[1]})
            $(card).click({id:current[1], src : current[0]}, choose);
            $(bucket).append(card)
        }
        $canvas.append(bucket);
    }

    async function choose(event){
        if (chosen === this || lock) {
            return;
        }

        $(this).attr("src", event.data.src);

        if (chosen == null) {
            chosen = this;
            return;
        }

        lock = true;

        await validate(chosen, this);

        lock = false;
        chosen = null;
        await checkEnd();
    }

    async function checkEnd(){
        if (count >= deckSize) {
            gameWon = true;
            audio.pause();
            $("#gamearea").addClass("d-none");
            $("#youWon").removeClass("d-none");

            await timeout(1500);

            if (config.options.completionURL) {
                window.location.href = config.options.completionURL;
            }
        }
    }

    async function validate(first, chosen){
        let correct = $(first).attr("data-val") === $(chosen).attr("data-val");
        if (correct) {
            correctAns();
        }

        await timeout(1500);

        if (correct){
            $(first).attr("src", blank);
            $(chosen).attr("src", blank);
            $(first).off();
            $(chosen).off();
        } else{
            $(first).attr("src", back);
            $(chosen).attr("src", back);
        }
    }

    function correctAns(){
        matched = true;
        count++;
        $("#matches").text(count)
    }

    function init() {
        stack_cards()
        $("#introGame").hide()
        // $(".game").show()
        $("#gamearea").addClass("gamearea");
        $(".game").removeClass("d-none");
        startTime = new Date();
        startTime = Number(startTime.getTime());
        if (config.options.backgroundSound) {
            audio.playAudioFile(config.options.backgroundSound);
        }
        timer = setInterval(countDown, 1000);
    }

    $("#play").on("click", init);
    document.getElementById('tryagain').addEventListener('click', () => {
        window.location.reload();
    });


});

export {setConfig};