// retoor <retoor@molodetz.nl>

import { Component } from "./Component.js";
import { Http } from "../Http.js";

const OPTION_KINDS = ["single_choice", "multiple_choice", "fill_blank", "ordering", "matching"];

const GROUP_FOR_KIND = {
    single_choice: ["options"],
    multiple_choice: ["options"],
    true_false: ["true_false"],
    free_text: ["free_text"],
    fill_blank: ["options", "fill_blank"],
    numeric: ["numeric"],
    ordering: ["options"],
    matching: ["options"],
};

export class AppQuizBuilder extends Component {
    connectedCallback() {
        this._slug = this.attr("data-quiz-slug");
        this._picker = this.querySelector("[data-quiz-kind-picker]");
        this._groups = Array.from(this.querySelectorAll("[data-quiz-kind-fields]"));
        this._form = this.querySelector("[data-quiz-question-form]");
        if (this._picker) {
            this._picker.addEventListener("change", () => this._applyKind());
            this._applyKind();
        }
        if (this._form) {
            this._form.addEventListener("submit", (event) => this._submit(event));
        }
    }

    _applyKind() {
        const kind = this._picker.value;
        const visible = GROUP_FOR_KIND[kind] || [];
        this._groups.forEach((group) => {
            group.hidden = !visible.includes(group.dataset.quizKindFields);
        });
        this._markRequired(kind);
    }

    _markRequired(kind) {
        const options = this.querySelector("[name=options]");
        if (options) options.required = OPTION_KINDS.includes(kind);
    }

    async _submit(event) {
        event.preventDefault();
        const button = this._form.querySelector("button[type=submit]");
        if (button) button.disabled = true;
        const params = [];
        new FormData(this._form).forEach((value, key) => params.push([key, value]));
        try {
            await Http.sendForm(`/quizzes/${this._slug}/questions`, params);
        } catch (error) {
            if (button) button.disabled = false;
            return;
        }
        window.location.reload();
    }
}

customElements.define("dp-quiz-builder", AppQuizBuilder);
