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

export class ActiveEffectSheet extends HandlebarsApplicationMixin(DocumentSheetV2) {

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

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

    static async #openEffect(evt) {
        evt.preventDefault()
        const {id} = evt.srcElement.dataset
        const effect = await this.document.effects.get(id)
        effect.sheet.render(true)
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)

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

        return options
    }

    /**
     * Handle form submission
     * @this {AdvantageSheet}
     * @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)
        context.system = context.document.system

        const effects = context.document.getEmbeddedCollection("ActiveEffect").contents
        if (effects.length > 0) {
            context.effectId = effects[0]._id
        }

        context.name = context.document.name
        context.img = context.document.img
        context.notes = context.document.system.notes

        return context
    }
}