import {Talent} from "../data/talent.mjs";

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


/**
 * @typedef TokenDistance
 * @property {Number} x
 * @property {Number} y
 * @property {Number} d
 * @property {Token} token
 */

export class BattleDialog extends HandlebarsApplicationMixin(ApplicationV2) {

    static DEFAULT_OPTIONS = {
        classes: ['dsa41', 'dialog', 'battle'],
        tag: "form",
        position: {
            width: 640,
            height: 518
        },
        window: {
            resizable: false,
        },
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: BattleDialog.#onSubmitForm
        },
        actions: {
            selectOffenseActor: BattleDialog.#setOffenseActor,
            selectDefenseActor: BattleDialog.#setDefenseActor,
            doBattle: BattleDialog.#doBattle,

        }
    }

    static PARTS = {
        form: {
            template: 'systems/DSA_4-1/templates/dialog/battle-dialog.hbs',
        }
    }

    /**
     * @type {Actor}
     * @private
     */
    _offenseActor = null
    _defenseActor = null

    constructor() {
        super()
    }


    static async #onSubmitForm(event, form, formData) {
        event.preventDefault()

        this._offenseTalent = formData.object['offense.talent']
        this._defenseTalent = formData.object['defense.talent']
    }

    static #setOffenseActor(event, target) {
        const {id} = target.dataset

        this._offenseActor = game.actors.get(id)
        this.render({parts: ["form"]})
    }


    static #setDefenseActor(event, target) {
        const {id} = target.dataset

        this._defenseActor = game.actors.get(id)
        this.render({parts: ["form"]})
    }

    static async #doBattle(event, target) {

        // TODO perform Dice Rolls but in secret mode so its up to the GM if they want to display the result or not

        let offenseTalent = {}

        if (this._offenseActor && this._offenseActor.items.get(this._offenseTalent)) {
            const skill = this._offenseActor.items.get(this._offenseTalent)
            offenseTalent.name = skill.name
            offenseTalent.taw = skill.system.taw
            offenseTalent.probe = skill.system.probe
        } else {
            offenseTalent.name = this.element.querySelector('input[name="offense.talent.name"]').value
            offenseTalent.taw = this.element.querySelector('input[name="offense.talent.taw"]').value
            offenseTalent.probe = [
                this.element.querySelector('input[name="offense.talent.probe.0.name"]').value,
                this.element.querySelector('input[name="offense.talent.probe.1.name"]').value,
                this.element.querySelector('input[name="offense.talent.probe.2.name"]').value
            ]
        }

        offenseTalent.eigenschaften = {}

        if (this._offenseActor && this._offenseActor.system.attribute) {
            offenseTalent.eigenschaften = this._offenseActor.system.attribute
        } else {
            offenseTalent.eigenschaften = {
                mu: this.element.querySelector('input[name="offenseAttributes.mu"]').value,
                kl: this.element.querySelector('input[name="offenseAttributes.in"]').value,
                in: this.element.querySelector('input[name="offenseAttributes.kl"]').value,
                ch: this.element.querySelector('input[name="offenseAttributes.ch"]').value,
                ff: this.element.querySelector('input[name="offenseAttributes.ff"]').value,
                ge: this.element.querySelector('input[name="offenseAttributes.ge"]').value,
                ko: this.element.querySelector('input[name="offenseAttributes.ko"]').value,
                kk: this.element.querySelector('input[name="offenseAttributes.kk"]').value,

            }
        }

        let defenseTalent = {}

        if (this._defenseActor && this._defenseActor.items.get(this._defenseTalent)) {
            const skill = this._defenseActor.items.get(this._defenseTalent)
            defenseTalent.name = skill.name
            defenseTalent.taw = skill.system.taw
            defenseTalent.probe = skill.system.probe
        } else {
            defenseTalent.name = this.element.querySelector('input[name="defense.talent.name"]').value
            defenseTalent.taw = this.element.querySelector('input[name="defense.talent.taw"]').value
            defenseTalent.probe = [
                this.element.querySelector('input[name="defense.talent.probe.0.name"]').value,
                this.element.querySelector('input[name="defense.talent.probe.1.name"]').value,
                this.element.querySelector('input[name="defense.talent.probe.2.name"]').value
            ]
        }


        defenseTalent.eigenschaften = {}

        if (this._defenseActor && this._defenseActor.system.attribute) {
            defenseTalent.eigenschaften = this._defenseActor.system.attribute
        } else {
            defenseTalent.eigenschaften = {
                mu: this.element.querySelector('input[name="defenseAttributes.mu"]').value,
                kl: this.element.querySelector('input[name="defenseAttributes.in"]').value,
                in: this.element.querySelector('input[name="defenseAttributes.kl"]').value,
                ch: this.element.querySelector('input[name="defenseAttributes.ch"]').value,
                ff: this.element.querySelector('input[name="defenseAttributes.ff"]').value,
                ge: this.element.querySelector('input[name="defenseAttributes.ge"]').value,
                ko: this.element.querySelector('input[name="defenseAttributes.ko"]').value,
                kk: this.element.querySelector('input[name="defenseAttributes.kk"]').value,

            }
        }


        const offense = await (new Talent(offenseTalent)).evaluate("gmroll")
        const defense = await (new Talent(defenseTalent)).evaluate("gmroll")

        offense.evaluatedRoll.toMessage({
            speaker: ChatMessage.getSpeaker({actor: this._offenseActor}),
            flavor: `Talent: ${offenseTalent.name}<br/>TaP: ${offense.tap}<br/>${offense.meisterlich ? "Meisterlich" : ""}${offense.patzer ? "Petzer" : ""}`,
        })
        defense.evaluatedRoll.toMessage({
            speaker: ChatMessage.getSpeaker({actor: this._defenseActor}),
            flavor: `Talent: ${defenseTalent.name}<br/>TaP: ${defense.tap}<br/>${defense.meisterlich ? "Meisterlich" : ""}${defense.patzer ? "Petzer" : ""}`,
        })

        this.close()
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)
        if (options.window) {
            options.window.title = "Vergleichende Proben"
        }
        return options
    }


    async _prepareContext(options) {
        const context = await super._prepareContext(options)
        context.actors = game.actors.filter(actor => actor.type === "Character" || actor.type === "Creature")

        context.offenseTalent = this._offenseTalent ?? ''
        context.offenseTalents = {}

        if (this._offenseActor) {
            context.offenseActor = this._offenseActor._id

            if (this._offenseActor.system.attribute) {
                context.offenseAttributes = {}
                Object.entries(this._offenseActor.system.attribute)?.forEach(([key, eigenschaft]) => {
                    context.offenseAttributes[key] = eigenschaft?.aktuell ?? 0
                })
            } else {
                context.offenseAttributes = false
            }

            if (this._offenseActor.itemTypes["Skill"]?.length > 0) {
                this._offenseActor.itemTypes["Skill"]?.forEach((skill) => {

                    if (skill.system.probe.length === 3) {
                        context.offenseTalents[`${skill.name}: ${skill.system.taw} (${skill.system.probe[0]}/${skill.system.probe[1]}/${skill.system.probe[2]})`] = skill.id
                    }
                })
            } else {
                context.offenseTalents = false
            }
        }

        context.defenseTalent = this._defenseTalent ?? ''
        context.defenseTalents = {}

        if (this._defenseActor) {
            context.defenseActor = this._defenseActor._id

            if (this._defenseActor.system.attribute) {

                context.defenseAttributes = {}
                Object.entries(this._defenseActor.system.attribute)?.forEach(([key, eigenschaft]) => {
                    context.defenseAttributes[key] = eigenschaft?.aktuell ?? 0
                })

            } else {
                context.defenseAttributes = false
            }
            if (this._defenseActor.itemTypes["Skill"]?.length > 0) {
                this._defenseActor.itemTypes["Skill"]?.forEach((skill) => {

                    if (skill.system.probe.length === 3) {
                        context.defenseTalents[`${skill.name}: ${skill.system.taw} (${skill.system.probe[0]}/${skill.system.probe[1]}/${skill.system.probe[2]})`] = skill.id
                    }
                })
            } else {
                context.defenseTalents = false
            }
        }

        return context
    }

    _onRender(context, options) {

    }


}