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

import * as dialog from "./dialog.js";
import {showDialogAsync} from "./dialog.js";

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

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

let setConfigHandler = new SetConfig();
function setConfig(config) {
    setConfigHandler.setConfig(config);
}

let config;
let nextButtonClick = null;
let currentHint = null;

function nextButton() {
    const {promise, resolve, reject} = Promise.withResolvers();
    nextButtonClick = resolve;
    return promise;
}

$("#next").on("click", function () {
    nextButtonClick?.();
    nextButtonClick = null;
});

$("#show-hint").on("click", hintButton);
async function hintButton(evt) {
    // let hintID = `hint-div-${currentHint}`;
    // $(`#${hintID}`).show7gen();
    // if (currentHint === 0 && config.hints.length > 1) {
    //     $("#hints").append(`<div id="more-hints-msg">More hints are available...</div>`)
    // }
    // currentHint++;
    // if (currentHint >= config.hints.length) {
    //     $("#more-hints-msg").remove()
    //     currentHint = null;
    //     $("#show-hint").hide7gen();
    // }
    showDialogAsync(config.hints[0]);
}

$(document).ready(async function () {
    /**** THIS CODE INCLUDES INSTRUCTIONAL AND ASSESSMENT CONTENT
     *    FOR THE SECOND PART OF ANY MULTI-STEP WORD PROBLEM
     *    WHERE THE SECOND STEP REQUIRES A DECISION, SUCH AS WHAT OPERATION TO USE
     *    WITH SCAFFOLDING AS NEEDED
     */
    config = await setConfigHandler.getConfigAsync();

    if ("title" in config.options) {
        $("#wp_title").html(`<h1>${config.options.title}</h1>`);
    }
    let screen= 0 ;
    let this_page_amount   ; // ENTER AMOUNT FOR PROBLEM HERE ;
    let quantity = parseInt(localStorage.getItem("quantity")); // VALUE FROM FIRST PROBLEM STEP ;
    $("#your_quantity").text("$" + quantity); // WILL SHOW VALUE OBTAINED IN PRIOR STEP ;

    /****  INFORMATIONAL CONTENT
     * CAN BE AS MANY LINES AS YOU LIKE OF 140 CHARACTERS OR LESS
     */
    // const text_boxes = config.textBoxes;

    // WILL SHOW THE FIRST LINE OF TEXT ON LOAD ;
    // $("#text_box").text(text_boxes[0]);

    /*** WHEN THE NEXT ARROW IS CLICKED THE TEXT WILL CHANGE ;
     *  EVERYTHING ELSE IN THIS FUNCTION IS OPTIONAL
     */
    for (let screen of config.problemScreens) {
        $("#text").html(`<p>${screen.text}</p>`);
        if ("image" in screen) {
            $("#image").html(`<img src="${screen.image}" >`)
        }
        await nextButton();
    }

    // $("#next").on("click", function () {
    //     screen++;
    //     $("#text_box").text(text_boxes[screen]);
    //
    //
    //     /*** CODE TO SHOW IMAGE  FOR SPECIFIC SCREENS
    //      *  SEE GRAPHIC NOVEL BLOCK FOR CODE TO CHANGE SRC OR IMAGE ON EACH SCREEN
    //      *  CASE 3 HIDES FOOTER AND FORCES PLAYER TO CHOOSE ONE OF TWO OPTIONS
    //      *  SEE DRAG AND DROP BLOCK FOR MULTIPLE OPTIONS
    //      */
    //
    //     switch (screen) {
    //         case 1:    $("#img_here").removeClass('invisible') ;
    //             break ;
    //
    //         case 3:
    //             $("#footer").addClass('invisible');
    //             $("#choices").removeClass('invisible') ;
    //             $('body').css('background-color','black');
    //             break ;
    //         case 5:
    //             window.location = "next_url.html";
    //             break ;
    //     }
    //     /** END OF OPTIONAL CODE **/
    // });

    $("#next").hide7gen();
    handleHints();

    // Now show the actual problem
    switch (config.options.problemType) {
        case "multiple choice":
            const {selectedVal, correct} = await showMultipleChoiceProblem();
            $("#next").show7gen();
            $("#hints").hide7gen();
            $("#show-hint").hide7gen();
            await playPostAnswerScreens(correct);
            break;

        case "number":
            const answer = await showNumberProblem();
            const numberAnswer = parseInt(answer, 10);
            $("#next").show7gen();

            await playPostAnswerScreens(numberAnswer === config.problem.correctAnswer);

            break;
    }

    async function showMultipleChoiceProblem() {
        const {question, answers, image} = config.problem;
        if (image) {
            $("#image").html(`<img src="${image}" >`)
        }

        const {selectedVal, correct} = await dialog.showMultipleChoiceQuestion({
            question, answers, parentDiv: "text"
        });

        return {selectedVal, correct};
    }

    async function showNumberProblem() {
        const {question, correctAnswer, image} = config.problem;
        if (image) {
            $("#image").html(`<img src="${image}" >`)
        }
        const answer = await dialog.showTextEntryDialog({prompt: question, parentDiv: "text"});

        return answer;
    }

    async function playPostAnswerScreens(correct) {
        if (correct) {
            // Show supplemental information if available
            const correctAnswerScreens = config?.correctAnswerScreens;
            if (correctAnswerScreens) {
                for (const screen of correctAnswerScreens) {
                    $("#text").html(`<p>${screen.text}</p>`);
                    if ("image" in screen) {
                        $("#image").html(`<img src="${screen.image}" >`)
                    }
                    await nextButton();
                }
                window.location.href = config.options.completionURL;
            }
        }
        else {
            // Show supplemental information if available
            const incorrectAnswerScreens = config?.incorrectAnswerScreens;
            if (incorrectAnswerScreens) {
                for (const screen of incorrectAnswerScreens) {
                    $("#text").html(`<p>${screen.text}</p>`);
                    if ("image" in screen) {
                        $("#image").html(`<img src="${screen.image}" >`)
                    }
                    await nextButton();
                }
                window.location.href = config.options?.incorrectAnswerURL ?? config.options.completionURL;
            }
        }
    }

    function handleHints() {
        if(!config?.hints || config.hints.length === 0) {
            return;
        }

        $("#hints").show7gen();
        $("#show-hint").show7gen();
        for(let [index, hint] of config.hints.entries()) {
            let hintID = `hint-div-${index}`;
            let hintElement = `<div id="${hintID}" class="hintDiv d-none"><div class="hint-text">${hint}</div></div>`;
            $("#hints").append(hintElement);
            $(`#${hintID}`).hide7gen();
        }

        currentHint = 0;
    }

    // CHOOSE CHOICE 1 OR 2;

    /***  CORRECT CHOICE
     *    REINFORCE CORRECT RESPONSE
     *    CONDUCT OPERATION BASED ON THEIR CHOICE
     *    SHOW FOOTER AGAIN FOR ADDITIONAL OPTIONAL INFORMATION
     *    TO EXPLAIN WHY THIS IS CORRECT RESPONSE
     *    OR JUST GO TO NEXT STEP, IF THERE IS ONE
     */
    $("#choice1").on("click", function () {
        $(this).text("THIS IS CORRECT");
        $("#more_choice").remove();
        $(".choice").css('background-color','white')
        $("#footer").removeClass('invisible');

        /*** THIS PERFORMS OPERATION WITH QUANTITY FROM PRIOR STEP
         * AND VALUE FOR PROBLEM ON THIS PAGE
         *  IN THIS EXAMPLE IT IS DIVIDING BUT ANY MATHEMATICAL OPERATION CAN BE PERFORMED
         *  THE NEW QUANTITY IS THEN STORED IN CASE THIS PROBLEM HAS MORE THAN TWO STEPS
         */
        quantity = quantity / this_page_amount ;
        let new_quantity = quantity.toString() ;
        localStorage.setItem("quantity",new_quantity);
        $("#your_quantity").text("$" + new_quantity);
        screen++;

        /*** IF GAME WILL WRITE TO DATABASE, CALL DATABASE BLOCK HERE
         *   IF PLAYED OFF-LINE OR WITHOUT LOGIN ONLINE DATABASE IS NOT NEEDED
         */
    });

    //  WRONG CHOICE ;
    $("#choice2").on("click", function () {
        /*** IF GAME WILL WRITE TO DATABASE, CALL DATABASE BLOCK HERE
         *   IF PLAYED OFF-LINE OR WITHOUT LOGIN ONLINE DATABASE IS NOT NEEDED
         *   WILL WRITE TO DATABASE BEFORE GOING TO CORRECTIVE SCREEN
         */
        window.location = "PAGE PROVIDING CORRECTIVE INSTRUCTION";

    });

});

export {setConfig}

