import {shuffle, getShuffledArray} from "./shuffle.js";
import $ from "./jquery.module.js";
import * as dialog from "./dialog.js";
import SetConfig from "./set_config_class.js";
import * as audio from "./audio.js";
import {playAudioFile, setAudioFile} from "./audio.js";
import {getMathProblemGenerator} from "./math_operation_problems.js";
let setConfigHandler = new SetConfig();

function setConfig(config) {
    setConfigHandler.setConfig(config);
}
let options;
let mathProblem    ;
let gameWon = false;
let audioFile ;

/* OPTIONAL TIMER SECTION. ONLY USED IF TIMER SELECTED IN CONFIG FILE */
let timer ;
//let seconds  = options.seconds ; // Time remaining in game ;
let seconds = 60 ;
let gameTimer;
function startGame() {
    let successText = options.successText ;
    // Starts timer in div in header. Counts down every second  ;
    function countdown () {
        gameTimer  = setInterval(function(){
            seconds--;
            (seconds === 1) ? $("#plural").text("") : $("#plural").text("s") ;
            $("#countdown").text(seconds) ;
            if (seconds < 1) {
                gameOver() ;
            }
        },1000);

    }
    function gameOver() {
        clearTimeout(timer);
        clearInterval(gameTimer);
        dialog.showDialogAsync("<h1>Time's up! Try again</h1> ")
            .then(() => {window.location.reload()});
        $(".dialog7gen").css("border-radius","20px") ;
    }
        countdown() ;


    /* END OPTIONAL TIMER SECTION */


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



    const generateDivisionProblems = () => {

        const problems = [];
        while (problems.length < 5) {
            let value = mathProblem.getProblem();
            let pair = mathProblem.correctAnswer;
            // Check if the value already exists in the problems array
            if (!problems.some(problem => problem.value === value)) {
                problems.push({ value, pair });
            }

        }
        return problems.flatMap(problem => [
            { value: problem.value, pair: problem.pair },
            { value: problem.pair, pair: problem.value }
        ]);
    };

        const cards = generateDivisionProblems();
        let flippedCards = [];
        let matchedPairs = 0;


        const createBoard = () => {
        const gameBoard = document.getElementById('game-board');
        let shuffledCards = getShuffledArray(cards);
            shuffledCards.forEach(card => {
            const cardElement = document.createElement('div');
            cardElement.classList.add('card');
            cardElement.dataset.value = card.value;
            cardElement.dataset.pair = card.pair;
            cardElement.addEventListener('click', flipCard);
            gameBoard.appendChild(cardElement);
            });
        };



        const flipCard = event => {
        const card = event.target;
        if (card.classList.contains('flipped')) return;
        if (flippedCards.length < 2) {
            card.innerHTML = card.dataset.value;
            card.classList.add('flipped');
            flippedCards.push(card);
        }


        if (flippedCards.length === 2) {
        setTimeout(checkMatch, 1000);
        }
        };



        const checkMatch = () => {
        const [card1, card2] = flippedCards;

        if (card1.dataset.pair === card2.dataset.value || card2.dataset.pair === card1.dataset.value) {
        matchedPairs++;
        document.getElementById('matches').innerText = matchedPairs.toString();
        if (matchedPairs === 5) {
            dialog.showDialog(
                "<h1>"+ successText + "</h1> ",
               () => {window.location.href = options.completionURL});
        }
    } else {
        card1.textContent = '';
        card2.textContent = '';
        card1.classList.remove('flipped');
        card2.classList.remove('flipped');
    }
        flippedCards = [];
    };
    createBoard() ;
    audio.playAudioFile(audioFile) ;
}
// Use the values assigned in the config.js file in the options object ;
$(() => {
    setConfigHandler. then((config)=>{
        options = config.options ;
       mathProblem = getMathProblemGenerator(config.mathProblems.problems);

       const instructDiv = document.getElementById("instructionsText");
        instructDiv.innerHTML = config.options.instructionsPage1 ;
        $("#play").on("click", ()=>{
            const instructions = document.querySelector("#instructions1") ;
            audioFile =  config.options.backgroundSound
            instructions.remove() ;
            startGame() ;
     });
    });

});

export {setConfig};