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

export class DeitySheet extends HandlebarsApplicationMixin(DocumentSheetV2) {

    /** @inheritDoc */
    static DEFAULT_OPTIONS = {
        position: {width: 520, height: 848},
        classes: ['dsa41', 'sheet', 'item', 'deity'],
        tag: 'form',
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
            handler: DeitySheet.#onSubmitForm
        },
        window: {
            resizable: true,
        },
        actions: {
            editImage: DocumentSheetV2.DEFAULT_OPTIONS.actions.editImage,
            openLiturgy: DeitySheet.#openLiturgySheet,
            removeLiturgy: DeitySheet.#removeLiturgy,
        }
    }

    /** @inheritDoc */
    static PARTS = {
        form: {
            template: `systems/DSA_4-1/templates/item/deity-sheet.hbs`
        },
    }

    /**
     * Handle form submission
     * @this {SpeciesSheet}
     * @param {SubmitEvent} event
     * @param {HTMLFormElement} form
     * @param {FormDataExtended} formData
     */
    static async #onSubmitForm(event, form, formData) {
        event.preventDefault()

        formData.object["system.miraclePlus"] = formData.object.miraclePlus.split(",")
        formData.object["system.miracleMinus"] = formData.object.miracleMinus.split(",")

        delete formData.object.miraclePlus
        delete formData.object.miracleMinus

        await this.document.update(formData.object) // Note: formData.object
    }

    static async #openLiturgySheet(event, target) {
        const {rank, liturgyId} = target.dataset
        if (liturgyId && rank) {
            this.document.system.liturgies["rank" + rank].find(p => p._id === liturgyId)?.sheet.render(true, {editable: false})
        }
    }

    static async #removeLiturgy(event, target) {
        const {rank, liturgyId} = target.dataset
        if (liturgyId && rank) {
            const idx = this.document.system.liturgies["rank" + rank].findIndex(p => p._id === liturgyId)
            this.document.system.liturgies["rank" + rank].splice(idx, 1)
            const thisUpdateObject = {}
            thisUpdateObject["system.liturgies.rank" + rank] = this.document.system.liturgies
            this.document.update(thisUpdateObject)
            this.render({parts: ["form"]})
        }
    }

    _configureRenderOptions(options) {
        super._configureRenderOptions(options)

        if (options.window) {
            options.window.title = this.document.name
        }

        return options
    }

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

        // const context = await super._prepareContext(options)
        context.system = this.document.system

        context.name = this.document.name
        context.img = this.document.img
        context.description = this.document.description

        context.liturgies = {
            rank0: [],
            rank1: [],
            rank2: [],
            rank3: [],
            rank4: [],
            rank5: [],
            rank6: [],
            rank7: [],
            rank8: [],
        }

        context.miraclePlus = this.document.system.miraclePlus?.join(",")
        context.miracleMinus = this.document.system.miracleMinus?.join(",")

        this.document.system.liturgies.rank0.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank0.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank1.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank1.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank2.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank2.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank3.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank3.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank4.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank4.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank5.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank5.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank6.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank6.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank7.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank7.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        this.document.system.liturgies.rank8.forEach(liturgyUuid => {
            fromUuid(liturgyUuid).then(liturgy => {
                context.liturgies.rank8.push({
                    id: liturgy._id,
                    name: liturgy.name,
                })
            })
        })

        return context
    }


    async _canDragDrop() {
        return true
    }

    _onRender(context, options) {
        new foundry.applications.ux.DragDrop.implementation({
            dropSelector: ".liturgy-drops",
            permissions: {
                drop: this._canDragDrop.bind(this)
            },
            callbacks: {
                drop: this._onDrop.bind(this)
            }
        }).bind(this.element);
    }

    async _onDrop(event, target) {
        const data = TextEditor.implementation.getDragEventData(event);
        const documentClass = foundry.utils.getDocumentClass(data.type)
        if (documentClass) {
            const document = await documentClass.fromDropData(data);

            if (document.type === "Liturgy") {
                // process and drop it rightly
                const {rank} = event.target.dataset
                if (rank) {
                    let rankData = this.document.system.liturgies["rank" + rank]
                    rankData.push(document.uuid)
                    const updateData = {}
                    updateData["system.liturgies.rank" + rank] = rankData
                    this.document.update(updateData)
                    this.render({parts: ["form"]})
                }

            }
        }
    }

}