import {XmlImport} from "../xml-import/xml-import.mjs";
import {SpecialAbility} from "../documents/specialAbility.mjs";

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

export class MeditatingDialog extends HandlebarsApplicationMixin(ApplicationV2) {

    static DEFAULT_OPTIONS = {
        classes: ['dsa41', 'dialog', 'meditating'],
        tag: "form",
        position: {
            width: 320,
            height: 433
        },
        window: {
            resizable: false,
            title: 'Meditieren'
        },
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
        },
    }

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

    /**
     * @type {Actor}
     * @private
     */
    _actor = null

    constructor(actor) {
        super();
        this._actor = actor
    }

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

    }

    #hatSonderfertigkeit(name) {
        return this._actor.itemTypes["SpecialAbility"]?.find(p => p.name === name) != null
    }

    async _prepareContext(options) {
        const context = await super._prepareContext(options)

        context.hasAstraleMeditation = this.#hatSonderfertigkeit("Astrale Meditation")
        context.hasThonnys = false



        context.rituale = {}

        this._actor.itemTypes["SpecialAbility"]?.filter(p => p.name.startsWith("Ritualkenntnis")).forEach( p => {
            context.rituale[p.name] = p.name.split("Ritualkenntnis:")[1].trim()
        })

        context.duration = "0"
        context.costs = "0 + 1d3"
        context.result = 0

        return context
    }


    #update(context) {
        // params
        const aspregain = this.element.querySelector('[name="aspRegain"]').value
        const thonnys = !!this.element.querySelector('[name="thonnys"]:checked')
        const astralmeditation = !!this.element.querySelector('[name="astralmeditation"]:checked')
        const talent = this.element.querySelector('[name="skill"]').value
        const rituale = this._actor.itemTypes["SpecialAbility"]?.filter(p => p.name.startsWith("Ritualkenntnis"))

        let wert = rituale.find( p => context.rituale[talent])?.system.value.split(talent + ": ")[1].trim() ?? null

        let ritualWert = 0

        if (!wert) {
            console.log("Ritualkenntniswert nicht gefunden für", talent)
            // maybe its actually a talent?

            const actualTalent = this._actor.itemTypes["Skill"].find(p => p.name === talent)
            if (actualTalent) {
                wert = actualTalent.system.taw
                ritualWert = wert + "/2"
            }
        } else {
            ritualWert = Number(wert)
        }

        // outputs
        const probe = this.element.querySelector("[name='talentprobe']")
        const dauer = this.element.querySelector("[name='duration']")
        const costs = this.element.querySelector("[name='costs']")
        const result = this.element.querySelector("[name='result']")

        let penalty
        let bonus = " +"+ ritualWert

        if (astralmeditation && thonnys) {
            bonus = " +" + ritualWert + " +3"
        }

        if (astralmeditation && thonnys) {
            penalty = ""
        } else {
            penalty = " +1d3"
        }

        probe.value = "IN/CH/KO " + bonus
        costs.value = ""+aspregain + penalty + " LeP"
        dauer.value = aspregain + " Spielrunden"
        result.value = aspregain + " AsP"

    }

    _onRender(context, options) {
        this.#update(context)

        this.element.querySelectorAll('[name="thonnys"], [name="astralmeditation"], [name="skill"], [name="aspRegain"]').forEach(e => e.addEventListener('change', (event) => {
            this.#update(context)
        }))

    }
}