const {HandlebarsApplicationMixin} = foundry.applications.api
const {ActorSheetV2} = foundry.applications.sheets

export class CreatureSheet extends HandlebarsApplicationMixin(ActorSheetV2) {

    /** @inheritDoc */
    static DEFAULT_OPTIONS = {
        position: {width: 520, height: 480},
        classes: ['dsa41', 'sheet', 'actor', 'creature'],
        tag: 'form',
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: CreatureSheet.#onSubmitForm
        },
        actions: {
            removeAttack: CreatureSheet.#removeAttack,
            addAttack: CreatureSheet.#addAttack,
            roll: CreatureSheet.#dieRoll,
            editImage: ActorSheetV2.DEFAULT_OPTIONS.actions.editImage,

        }
    }

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

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

    /**
     * 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
    }

    static async #removeAttack(evt) {
        const {index} = evt.srcElement.dataset;
        let sans = Array.from(this.document.system.attacks);
        sans.splice(index, 1);
        await this.document.update({'system.attacks': sans})
    }

    static async #dieRoll(evt) {
        const {rollType, rollName, roll} = evt.srcElement.dataset;
        let r = new Roll(roll, this.document.getRollData());
        const label = `${rollType} (${rollName})`
        await r.toMessage({
            speaker: ChatMessage.getSpeaker({actor: this.document}),
            flavor: label,
            rollMode: game.settings.get('core', 'rollMode'),
        });
    }

    static async #addAttack() {
        const name = this.element.querySelector('#attack_name').value
        const at = this.element.querySelector('#attack_at').value
        const pa = this.element.querySelector('#attack_pa').value
        const tp = this.element.querySelector('#attack_tp').value

        const newAttack = {
            name,
            at,
            pa,
            tp
        }

        await this.document.update({'system.attacks': [...this.document.system.attacks, newAttack]})

        this.element.querySelector('#attack_name').value = ""
        this.element.querySelector('#attack_at').value = ""
        this.element.querySelector('#attack_pa').value = ""
        this.element.querySelector('#attack_tp').value = ""
    }

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

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

        context.attacks = [];
        context.actor = actorData;

        actorData.system.attacks.forEach((attack, index) => {
            context.attacks.push({
                namepath: `system.attacks.${index}.name`,
                name: attack.name,
                atpath: `system.attacks.${index}.at`,
                at: attack.at,
                papath: `system.attacks.${index}.pa`,
                pa: attack.pa,
                tppath: `system.attacks.${index}.tp`,
                tp: attack.tp,
                index: index,

            })
        })

        return context;
    }

}
