import $ from "./jquery.module.js";
import * as caves_and_trees from "./caves_and_trees_lib.js";
import SetConfig from "./set_config_class.js";
import {shuffle} from "./random.js";

let setConfigHandler = new SetConfig();
const answerLabels = "abcdefghijklmnopqrstuvwxyz".split("");

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

function getProblem() {
    if (this.nextQuestion >= this.questions.length) {
        this.nextQuestion = 0;
        if (this.randomizeQuestions) {
            shuffle(this.questions);
        }
    }

    let q = this.questions[this.nextQuestion++];
    let displayedQuestion = `<div class="question-multiple-7gen">Q: ${q.question}${q.question.endsWith("?") ? "" : "?"}</div>`;
    for (let [index, answer] of q.answers.entries()) {
        const label = answerLabels[index];
        if (answer[0] === this.rightAnswerFlag) {
            answer = answer.substring(1);
            this.correctAnswer = {label, index};
        }
        const id7gen = `7gen-${label}`;
        displayedQuestion += `
            <div class="answer-multiple-7gen">
                <input type="radio" name="choice-7gen" id="${id7gen}" value="${index}">
                <label for="${id7gen}">${answer}</label>
            </div>
        `;
    }

    return displayedQuestion;
}

function getMultipleChoiceQuestionsGenerator({questions, rightAnswerFlag = "*", randomizeQuestions = true}) {
    // THe question list "questions" usually comes from a config file. It should be an array
    // where each entry has the form:
    //  {
    //      question: "What is the answer?",
    //      answers: ["answer1", "answer2", "answer3", "answer4"],  // Array of answers
    //   }
    //
    // The correct answer is flagged in the answer itself. The first character of the correct answer
    // should be the "rightAnswerFlag" character, which will be stripped off when the answer is
    // displayed. By default the rightAnswerFlag character is "*".

    if (randomizeQuestions) {
        shuffle(questions);
    }

    const problem = {
        questions,
        rightAnswerFlag,
        randomizeQuestions,
        nextQuestion: 0,
        correctAnswer: "",
        getProblem
    }

    return problem;
}

function submitAnswer(event) {
    let selectedVal = null;
    let selected = $("input[type='radio'][name='choice-7gen']:checked");
    if (selected.length > 0) {
        selectedVal = parseInt(selected.val(), 10);
    }
    $("#problemBox").hide7gen();
    let correctAnswer = caves_and_trees.getCorrectAnswer();
    caves_and_trees.questionAnswered(correctAnswer.index === selectedVal);
}

$(document).ready(async function(){
    let config = await setConfigHandler.configPromise;
    const rightAnswerFlag = config.options?.rightAnswerFlag ?? "*";
    const randomizeQuestions = config.options?.randomizeQuestions ?? true;
    let easyProblem = getMultipleChoiceQuestionsGenerator({questions: config.questions.easy, rightAnswerFlag, randomizeQuestions});
    let hardProblem = getMultipleChoiceQuestionsGenerator({questions: config.questions.hard, rightAnswerFlag, randomizeQuestions});

    function getProb(difficulty) {
        let problem = (difficulty === "easy") ? easyProblem : hardProblem;
        $("#answerText").val("").focus();
        $("#output").hide7gen();
        // $("#problemArea").show7gen();
        $("#problemBox").show7gen();
        let problemHTML = problem.getProblem();
        $("#problem-question").html(problemHTML);
        return problem.correctAnswer;
    }

    $("#submit-choice-7gen").on("click", submitAnswer);

    caves_and_trees.setConfig({config, easyProblem, hardProblem, getProb});
});

export {setConfig};