//import {_config} from "../../blocks/memory_game/memory_config.js";
// import $ from "../../_base/js/jquery.module.js";
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";
let setConfigHandler = new SetConfig();

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

    let options;
    let cards_config ;
    let div_array = [] ;
    let card_front  ;
    let num_matches = 5; // Number of matches to select from array and display ;
    let second_card ; // checks if second card in pair for deck dealing purposes ;
    let div_add ;
    let randomize = 1 ;
    let allItems ;
    let first_turn = 1 ; // Check for if there is already a card turned over ;
    let match_num  ; // Used to check if the two cards match ;
    let match_num2 ; // Number for second card turned over ;
    let matches = 0 ;
    let first_id ; // Tracks card to turn back over if not a match ;
    let second_id ;
    let wait = 0 ; // Used to enforce wait until two unmatched cards flip back over before clicking another card.
    let timed = 1 ;


function startGame() {
    let cards = cards_config.card_array ;
    let correct_sound = options.correct_sound ;
    let successText = options.successText ;

    timed = options.timed ;
    /* OPTIONAL TIMER SECTION. ONLY USED IF TIMER SELECTED IN CONFIG FILE */
    let timer ;
    let seconds  = options.seconds ; // Time remaining in game ;
    let gameTimer;
    // 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") ;

        }
            if (timed === 1) {
                $("#timer").removeClass('d-none') ;
                countdown() ;
            }

    /* END OPTIONAL TIMER SECTION */

    // CREATES DIVS OF CARD PAIRS FOR HOWEVER MANY CARDS SPECIFIED IN NUM_MATCHES WITH FRONT WITH AN IMAGE FOR ONE CARD AND TEXT FOR THE OTHER ;
    // ATTACHES DATA TO EACH DIV FOR A CARD NUMBER AND MATCH (MAY NOT REALLY NEED THE CARD NUMBER ;
    // MATCH WILL BE USED LATER WHEN THE CLICK TO SEE IF THE TWO CARDS MATCH ;
    // PUSHES ALL DIVS TO ARRAY ;
    // NOTE -- RIGHT NOW, CARD PAIRS ARE PULLED FROM THE ARRAY ABOVE IN ORDER, NOT RANDOMLY, SHOULD CHANGE THAT ;
    for (let i=0; i < num_matches ; i++) {
        let data_front = `<img src='${cards[i].card_front1}' class='card-image' alt='${cards[i].alt}'>`;
        if ("card_front1_caption" in cards[i]) {
            data_front += `<div class='card-caption'>${cards[i].card_front1_caption}</div>`;
        }
        div_add = `<div class="card-div cards"  id ="card${i}" data-card="${i}" data-match="${i}" data-front="${data_front}" </div> `;
        div_array.push(div_add) ;
        second_card = i + num_matches ;
        div_add = "<div class='card-div cards vertical-center text-center fs-4' id ='card" + i + "a' data-card ='" + second_card + "' data-match ='" + i + "' data-front = '" + cards[i].card_front2 + "'></div>" ;
        div_array.push(div_add) ;
    }

    //  SHUFFLES ARRAY USING IMPORTED SHUFFLE.JS MODULE
    if (randomize === 1) {
        allItems = (randomize) ? getShuffledArray(div_array) : div_array;
    }

    // PUTS num_matches RANDOM CARDS IN THE FIRST ROW AND ANOTHER num_matches IN THE SECOND
    for (let i=0; i < num_matches ; i++){
        $("#first_row").append(allItems[i]) ;
    }
    for (let i= num_matches; i < 2*num_matches ; i++){
        $("#second_row").append(allItems[i]) ;
    }
    
    /* SHOWS CARD FRONT WHEN CLICKED. If first card, saves number for match
        if second card, compares number with saved number. If it is a match, increments match number.
        **** Flipping over the card when it is not a match isn't working yet
     */

    $(".cards").on("click", async function(){
        if( !$(this).hasClass('cards') || wait === 1) {
            return ;
        }
        card_front = $(this).data('front') ;
        $(this).html(card_front).css('background-color','white') ;
        if (first_turn === 1) {
            match_num = $(this).data('match') ;
            first_id = "#" + $(this).attr('id') ;
            first_turn = 0 ;
        }
        else {
            wait = 1 ;
            match_num2 = $(this).data('match') ;
            second_id = "#" + $(this).attr('id') ;
            first_turn = 1 ;
            // IF IT'S A MATCH, INCREASE THE MATCHES NUMBER AND DON'T COUNT ANY FUTURE CLICKS ON THESE CARDS;
            if(match_num2 === match_num){
                matches++ ;
                $(first_id).removeClass('cards') ;
                $(second_id).removeClass('cards') ;
                wait = 0 ;
                $("#num_matches").text(matches);
                if (correct_sound.length > 0 ){
                    setAudioFile(correct_sound) ;
                    audio.play(true) ;
                }

                if (matches === num_matches) {
                    clearTimeout(timer);
                    clearInterval(gameTimer);
                    await dialog.showDialogAsync("<h1>"+ successText + "</h1> ");
                    if ("completionFunction" in options) {
                        await options.completionFunction();
                    }
                    window.location.href = options.completionURL;

                    $(".dialog7gen").css("border-radius","20px") ;
                }
            }
            if (match_num2 !== match_num) {
                $(first_id).css('background-color','red') ;
                $(second_id).css('background-color','red') ;
                setTimeout(function(){
                    $(first_id).empty().css('background-color','blue') ;
                    $(second_id).empty().css('background-color','blue') ;
                    wait = 0 ;
                },1500) ;
            }
        }
    });
    /* END MATCHING CARD SECTION */
}

    // Use the values assigned in the config.js file in the options object ;
$(() => {
    setConfigHandler. then((config)=>{
        options = config.options ;
        cards_config = config.cards_config ;
        const instructDiv = document.getElementById("instructionsText");
        instructDiv.innerHTML = config.options.instructionsPage1 ;
        if ("numMatches" in options) {
            num_matches = options.numMatches;
        }
        if (num_matches === 4) {
            $("#first_row").removeClass("grid").addClass("grid4");
            $("#second_row").removeClass("grid").addClass("grid4");
        }

        $("#play").on("click", ()=>{
            const instructions = document.querySelector("#instructions1") ;
            instructions.remove() ;

            startGame() ;
        });
    });

});

export {setConfig};


