<script>
    import QuestionManager from "../stores";
    const { activeQuestion } = QuestionManager;

    import { QuestionTypes } from "../data";

    import SelectOne from "./questions/SelectOne.svelte";
    import SelectMultiple from "./questions/SelectMultiple.svelte";
    import AssignValues from "./questions/AssignValues.svelte";
    import TextInput from "./questions/TextInput.svelte";

    const questions = new Map();
    questions.set(QuestionTypes.SelectOne, SelectOne);
    questions.set(QuestionTypes.SelectMultiple, SelectMultiple);
    questions.set(QuestionTypes.AssignValues, AssignValues);
    questions.set(QuestionTypes.TextInput, TextInput);

    $: question = $activeQuestion.question;
    $: component = questions.get(question.type);

    let showResult = false;
    let isCorrect = false;

    let idx = 0;

    function next() {
        idx++;
        if (isCorrect) {
            isCorrect = false;
            $activeQuestion.correct()
        } else {
            $activeQuestion.wrong();
        }
        showResult = false;
    }
</script>

{#if question}
    <div class="margin">
        <h2>{@html question.title}</h2>
    </div>
    {#each question.images as image}
        <div class="margin">
            <img src={image} style="width:100%;"/>
        </div>
    {/each}
    <div class="margin">
        <svelte:component key={idx} this={component} {question} {showResult} bind:isCorrect />
    </div>
    <div class="margin fl">
        {#if !showResult}
            <button class="btn lbtn" on:click={()=>showResult = true}>
                Check
            </button>
        {:else}
            <button class="btn lbtn" on:click={()=>next()}>
                Next
            </button>
        {/if}
    </div>
{/if}

<style>
    .fl {
        display: flex;
    }

    .lbtn {
        margin-left: auto;
    }
</style>