const {DocumentSheetV2, HandlebarsApplicationMixin} = foundry.applications.api

export class SkillSheet extends HandlebarsApplicationMixin(DocumentSheetV2) {

    /** @inheritDoc */
    static DEFAULT_OPTIONS = {
        position: {width: 520, height: 480},
        classes: ['dsa41', 'sheet', 'item', 'skill'],
        tag: 'form',
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: SkillSheet.#onSubmitForm
        }
    }

    static TABS = {
        sheet: {
            tabs: [
                {id: 'meta', group: 'sheet', label: 'Meta'},
                {id: 'description', group: 'sheet', label: 'Beschreibung'},
            ],
            initial: 'meta'
        }
    }

    /** @inheritDoc */
    static PARTS = {
        form: {
            template: `systems/DSA_4-1/templates/item/skill/main-sheet.hbs`
        },
        meta: {
            template: `systems/DSA_4-1/templates/item/skill/tab-meta.hbs`
        },
        description: {
            template: `systems/DSA_4-1/templates/item/skill/tab-description.hbs`
        }
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)

        if (options.window) {
            options.window.title = this.document.name
        }

        return options
    }

    /**
     * Handle form submission
     * @this {SkillSheet}
     * @param {SubmitEvent} event
     * @param {HTMLFormElement} form
     * @param {FormDataExtended} formData
     */
    static async #onSubmitForm(event, form, formData) {
        event.preventDefault()

        await this.document.update(formData.object) // Note: formData.object
    }

    /** @override */
    async _prepareContext(options) {

        const context = await super._prepareContext(options)
        const skillData = context.document;

        context.system = skillData.system;
        context.flags = skillData.flags;
        context.categoryOptions = {
            Gaben: "Gaben",
            Kampf: "Kampf",
            Körperlich: "Körperlich",
            Gesellschaft: "Gesellschaft",
            Natur: "Natur",
            Wissen: "Wissen",
            Sprachen: "Sprachen",
            Schriften: "Schriften",
            Handwerk: "Handwerk"
        }

        context.isCombat = skillData.system.gruppe === "Kampf"
        context.isTalent = skillData.system.gruppe !== "Kampf"
        context.isLanguage = skillData.system.gruppe === "Sprachen" || skillData.system.gruppe === "Schriften"
        context.hasRequirement = skillData.system.voraussetzung?.talent != null ?? false

        return context;
    }
}