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

export class SpecialAbilitySheet extends HandlebarsApplicationMixin(DocumentSheetV2) {

    /** @inheritDoc */
    static DEFAULT_OPTIONS = {
        position: {width: 520, height: 600},
        classes: ['dsa41', 'sheet', 'item', 'specialability'],
        tag: 'form',
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: SpecialAbilitySheet.#onSubmitForm
        },
        actions: {
            addRequirement: SpecialAbilitySheet.#addRequirement,
            removeRequirement: SpecialAbilitySheet.#removeRequirement,
            addMod: SpecialAbilitySheet.#addMod,
            removeMod: SpecialAbilitySheet.#removeMod,
            saveVariant: SpecialAbilitySheet.#saveVariant
        }
    }

    static TABS = {
        sheet: {
            tabs: [
                {id: 'specialability', group: 'sheet', label: 'Sonderfertigkeit'},
            ],
            initial: 'specialability'
        }
    }

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

    _instance = null

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)

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

        return options
    }

    constructor(...args) {
        super(...args);
        SpecialAbilitySheet._instance = this
    }

    static async #addRequirement(event, target) {
        const selections =
            "<option value='talentMin'>Mindest Talentwert</option>" +
            "<option value='talentMax'>Maximal Talentwert</option>" +
            "<option value='attributeMin'>Mindest Attributswert</option>" +
            "<option value='attributeMax'>Maximal Attributswert</option>" +
            "<option value='compare'>Vergleich</option>"

        const type = await foundry.applications.api.DialogV2.prompt({
            window: {title: "Neue Voraussetzung"},
            content: `<select name="type">${selections}</select>`,
            ok: {
                label: `Hinzufügen`,
                callback: (event, button, dialog) => button.form.elements.type.value
            }
        });

        if (type) {
            let newReq = {}
            switch (type) {
                case 'talentMin':
                    newReq = {
                        talent: 'Klettern',
                        minValue: '0'
                    }
                    break;
                case 'talentMax':
                    newReq = {
                        talent: 'Zechen',
                        maxValue: '0'
                    }
                    break;
                case 'attributeMin':
                    newReq = {
                        attribute: 'ge',
                        minValue: '0'
                    }
                    break;
                case 'attributeMax':
                    newReq = {
                        attribute: 'mu',
                        maxValue: '0'
                    }
                    break;
                case 'compare':
                    newReq = {
                        compare: {
                            ownAttribute: 'ini.aktuell',
                            operation: 'eq',
                            targetAttribute: 'ini.aktuell'
                        }
                    }
                    break;

            }

            const lastIndex = Object.keys(SpecialAbilitySheet._instance._currentSelectedVariant.requirements).length
            SpecialAbilitySheet._instance._currentSelectedVariant.requirements[lastIndex] = newReq
            SpecialAbilitySheet._instance.render({parts: ["form", "advantage", "variants"]})
        }
    }

    static async #removeRequirement(event, target) {

        const {index} = target.dataset

        if (index) {
            delete SpecialAbilitySheet._instance._currentSelectedVariant.requirements[index]
        }

    }

    static async #addMod(event, target) {
        const selections =
            "<option value='talent'>Talent</option>" +
            "<option value='talentGroup'>Talentgruppe</option>" +
            "<option value='attribute'>Attribute</option>" +
            "<option value='trait'>Merkmal</option>"

        const type = await foundry.applications.api.DialogV2.prompt({
            window: {title: "Neuer Modifikator"},
            content: `<select name="type">${selections}</select>`,
            ok: {
                label: `Hinzufügen`,
                callback: (event, button, dialog) => button.form.elements.type.value
            }
        });

        if (type) {
            let newReq = {}
            switch (type) {
                case 'talent':
                    newReq = {
                        talent: 'Klettern',
                        value: '0'
                    }
                    break;
                case 'talentGroup':
                    newReq = {
                        talentGruppe: 'Gesellschaft',
                        value: '0'
                    }
                    break;
                case 'trait':
                    newReq = {
                        merkmal: 'Elementar',
                        value: '0'
                    }
                    break;
                case 'attribute':
                    newReq = {
                        name: 'ge',
                        value: '0'
                    }
                    break;
            }

            const lastIndex = Object.keys(SpecialAbilitySheet._instance._currentSelectedVariant.mod).length
            SpecialAbilitySheet._instance._currentSelectedVariant.mod[lastIndex] = newReq
            SpecialAbilitySheet._instance.render({parts: ["form", "advantage", "variants"]})
        }
    }

    static async #removeMod(event, target) {

        const {index} = target.dataset

        if (index) {
            delete SpecialAbilitySheet._instance._currentSelectedVariant.mod[index]
        }
    }

    static async #saveVariant(event, target) {
        /**
         * @type {HTMLFormElement}
         */
        const form = AdvantageSheet._instance.form

        let flattenObject = {}

        Object.values(form).forEach(input => {
            if (input.name.startsWith('mod') || input.name.startsWith('requirements')) {
                flattenObject[`${input.name}`] = input.value
            }
            if (input.name === "vName") {
                flattenObject[`name`] = input.value
            }
        })


        let auswahl = SpecialAbilitySheet._instance.document.system.auswahl

        const fo = foundry.utils.expandObject(flattenObject)
        auswahl[AdvantageSheet._instance._currentSelectedVariantIndex] = {
            name: fo.name,
            mod: Object.values(fo.mod),
            requirements: Object.values(fo.requirements)
        }

        SpecialAbilitySheet._instance.document.update({system: {auswahl}})
    }
    
    /**
     * Handle form submission
     * @this {EquipmentSheet}
     * @param {SubmitEvent} event
     * @param {HTMLFormElement} form
     * @param {FormDataExtended} formData
     */
    static async #onSubmitForm(event, form, formData) {
        event.preventDefault()
        if (!form.querySelector('.tab.specialability.active')) {
            const obj = foundry.utils.expandObject(formData.object)

            if (obj.mod) this._currentSelectedVariant.mod = obj.mod
            if (obj.vName) this._currentSelectedVariant.name = obj.vName
            if (obj.requirements) this._currentSelectedVariant.requirements = obj.requirements

        } else {
            delete formData.object.mod
            delete formData.object.vName
            delete formData.object.requirements
            delete formData.object.variant
            await this.document.update(formData.object) // Note: formData.object
        }

        this.render({parts: ["form", "specialability", "variants"]})
    }

    _getTabsConfig(group) {
        const tabs = foundry.utils.deepClone(super._getTabsConfig(group))

        if (this.document.system.auswahl) {
            tabs.tabs.push({id: 'variants', group: 'sheet', label: 'Varianten'})
        }

        return tabs
    }

    /** @override */
    async _prepareContext(options) {
        const context = await super._prepareContext(options);

        const specialabilityData = context.document;

        context.system = specialabilityData.system;
        context.flags = specialabilityData.flags;
        context.text = specialabilityData.system.text;
        context.aktionsText = specialabilityData.system.aktionsText;
        context.hasChoices = context.system.auswahl.length > 0;
        context.choices = {}
        context.value = context.system.value
        context.system.auswahl.forEach(a => {
            context.choices[a.name] = a.name
        })
        context.isActive = this.document.system.isActive()?.passes
        context.mod = this.document.system.getActiveMod()?.map(mod => {
            return {
                name: mod.name,
                value: mod.value > 0 ? "+" + mod.value : mod.value,
            }
        })
        context.hasModality = context.system.value != null

        context.name = specialabilityData.name
        context.variantChoices = {}
        context.variants = []

        specialabilityData.system.auswahl?.forEach(variant => {
            context.variantChoices[variant.name] = variant.name
            context.variants.push(variant)
        })
        context.currentSelectedVariantName = this._currentSelectedVariant?.name
        context.currentSelectedVariant = this._currentSelectedVariant
        context.currentSelectedVariantIndex = this._currentSelectedVariantIndex


        return context;
    }

    _onRender(context, options) {
        if (this._selectedVariant == null) {
            this._selectedVariant = this.document.system.auswahl[0]?.name ?? ""
            this._currentSelectedVariant = this.document.system.auswahl?.find(p => p.name === this._selectedVariant)
            this._currentSelectedVariantIndex = this.document.system.auswahl?.findIndex(p => p.name === this._selectedVariant)
        }
        this.element.querySelector('select[name="variant"]').addEventListener('change', (event, target) => {
            if (event.target.value != this._selectedVariant) {
                this._selectedVariant = event.target.value
                this._currentSelectedVariant = this.document.system.auswahl?.find(p => p.name === this._selectedVariant)
                this._currentSelectedVariantIndex = this.document.system.auswahl?.findIndex(p => p.name === this._selectedVariant)
            }
        })
    }

}
