import {ATTRIBUTE, ATTRIBUTE_DESCRIPTIONS} from "../data/attribute.mjs";
import {displayRoll} from "../globals/displayRoll.js";

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

export class AttributeDialog extends HandlebarsApplicationMixin(ApplicationV2) {

    static DEFAULT_OPTIONS = {
        classes: ['dsa41', 'dialog', 'eigenschaft'],
        tag: "form",
        position: {
            width: 480,
            height: 800
        },
        window: {
            resizable: false,
            title: "Eigenschaft nutzen"
        },
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: AttributeDialog.#onSubmitForm
        },
        actions: {
            use: AttributeDialog.#use,
        }
    }


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

    static data = {}

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

    constructor(actor, attributeOrAdvantageId) {
        super()
        this._actor = actor
        const advantage = this._actor.itemTypes["Advantage"].find(p => p._id === attributeOrAdvantageId)
        if (advantage) {
            const badAttribute = advantage
            this._name = badAttribute.name
            this._value = badAttribute.system.value
            this._flaw = true
            this._symbol = "flaw"
            this._text = badAttribute.system.description
        } else {
            this._name = attributeOrAdvantageId.name
            this._value = this._actor.system.attribute[attributeOrAdvantageId.symbol.toLowerCase()].aktuell
            this._flaw = false
            this._symbol = attributeOrAdvantageId.symbol
            this._text = ATTRIBUTE_DESCRIPTIONS[attributeOrAdvantageId.symbol.toLowerCase()]
        }

        this._circumstance = 0
        this._mods = []
    }

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

        this._circumstance = formData.object["circumstance"]
        this._mods = []
        Object.entries(formData.object).filter(([key, value]) => key.startsWith("mods.")).forEach(([key, value]) => {
            const [_, suffix] = key.split("mods.")
            if (value != null) {
                this._mods.push({
                    name: suffix,
                    value: value
                })
            }

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


    static async #use(event, target) {


        let modValue = this._circumstance
        this._mods.forEach(mod => {
            modValue += Number(mod.value)
        })

        const targetValue = this._value + modValue

        let roll = await new Roll(`1d20`).evaluate()
        let diff = targetValue - roll.terms[0].results[0].result

        const context = {
            attribute: this._name,
            dieResult: roll.terms[0].results[0].result,
            target: targetValue,
            remaining: diff,

        }

        if(diff>0) {
            context.remaining = Math.abs(diff)
        } else if (diff===0) {
            context.remaining = 1
        } else {
            context.missing = Math.abs(diff)
        }

        await displayRoll(roll, game.user, this.actor, false, true, 'systems/DSA_4-1/templates/chat/attribute-chat-message.hbs', context)

        this.close()
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)

        if (options.window) {
            if (this._flaw) {
                options.window.title = `Schlechte Eigenschaft: ${this._name}`
            } else {
                options.window.title = `Eigenschaft: ${this._name}`
            }

            options.position.height = 640
        }


        return options
    }


    async _prepareContext(options) {
        const context = await super._prepareContext(options)
        context.actor = this._actor
        context.colorfulDice = game.settings.get('DSA_4-1', 'optional_colorfuldice')

        context.text = this._text

        context.dice = []

        if (this._flaw) {
            context.dice.push({
                wert: this._value,
                name: "",
                tooltip: "flaw",
            })
        } else {
            context.dice.push({
                wert: this._actor.system.attribute[this._symbol.toLowerCase()].aktuell,
                name: this._symbol.toUpperCase(),
                tooltip: ATTRIBUTE[this._symbol.toLowerCase()],
            })
        }

        context.mods = [] // ADV, DDV, SF that may influence this talent atleast BE

        const categories = ["Advantage", "SpecialAbility"]
        categories.forEach(category => this._actor.itemTypes[category].forEach(adv => {

            const mods = adv.system.getActiveMod()

            mods?.forEach(mod => {

                if (mod.name) {

                    if (mod.name === `attribute.${this._symbol.toLowerCase()}.mod`) {
                        context.mods.push({
                            name: adv.name,
                            value: mod.value,
                            mod: adv.name + "eigenschaft",
                            active: this._mods.find(mod => mod.name === adv.name + "eigenschaft")
                        })
                    }

                }

            })

        }))

        context.value = this._value
        context.circumstance = this._circumstance
        context.penalty = 0
        this._mods.forEach(mod => {
            context.penalty += Number(mod.value)
        })

        context.modResult = context.circumstance + context.penalty
        context.displayModResult = context.modResult > 0 ? `+${context.modResult}` : context.modResult

        return context
    }
}