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

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

export class XmlImportDialog extends HandlebarsApplicationMixin(ApplicationV2) {

    static DEFAULT_OPTIONS = {
        classes: ['dsa41', 'dialog', 'xmlimport'],
        tag: "form",
        position: {
            width: 320,
            height: 478
        },
        window: {
            resizable: false,
        },
        form: {
            submitOnChange: false,
            closeOnSubmit: true,
            handler: XmlImportDialog.#onSubmitForm
        },
    }

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

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

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

    static async #onSubmitForm(event, form, formData) {
        event.preventDefault()
        console.debug("Importing XML with following options", formData.object)

        const options = {}

        formData.object.importOption.forEach(p => {
            options[p] = true
        })

        const file = form.querySelector('input[type="file"]').files[0]

        try {
            form.querySelector('button[type="submit"]').setAttribute("disabled", true)
            await this._xmlImport.importCharacter(this._actor._id, file, options)
            form.querySelector('button[type="submit"]').setAttribute("disabled", false)
            return true
        } catch (e) {
            console.error(e)
            form.querySelector('button[type="submit"]').setAttribute("disabled", false)
            return false
        }
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)
        options.window.title = `${this._actor.name} importieren`
        return options
    }

    async _prepareContext(options) {
        const context = await super._prepareContext(options)
        context.options = XmlImport.getOptions()
        return context
    }

    _onRender(context, options) {

    }


}