export default {
    _prepareContext: (context, actor, thisObject) => {

        const actorData = context.document
        context.spells = []
        context.system = actorData.system
        context.flags = actorData.flags
        context.derived = context.document.system
        context.originalName = actorData.name
        context.name = context.derived.name ?? actorData.name
        context.effects = actorData.effects ?? []

        context.equipments = []
        context.carryingweight = 0
        actorData.itemTypes["Equipment"].sort((a, b) => a.sort - b.sort).forEach((item, index) => {

                // worn items are halved weight

                let effectiveWeight = item.system.weight ?? 0
            if (context.document.isWorn(item._id)) {
                    effectiveWeight = item.system.weight ? item.system.weight / 2 : 0
                }

                context.equipments.push({
                    index: index,
                    id: item._id,
                    quantity: item.system.quantity,
                    name: item.name,
                    icon: item.img ?? "",
                    weight: item.system.weight,
                    worn: context.document.isWorn(item._id)
                })
                context.carryingweight += item.system.quantity * effectiveWeight;

        })
        context.maxcarryingcapacity = actorData.system.attribute.kk.aktuell
        context.carryingpercentage = Math.min((context.carryingweight / context.maxcarryingcapacity) * 100, 100);

        context.wealth = 0

        actorData.itemTypes["Equipment"].forEach(coin => {
            if (coin.system.category.indexOf("Währung") !== -1) {
                context.wealth += (coin.system.quantity * coin.system.currencyDenominator)
            }
        })

        const maxSets = 3
        const romanNumerals = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]
        context.sets = []
        for (let setIndex = 0; setIndex < maxSets; setIndex++) {

            context.sets.push({
                tab: "pane" + (setIndex + 1),
                label: romanNumerals[setIndex],
                index: setIndex,
                actorId: actorData.id,
                setEquipped: actorData.system.setEquipped === setIndex,
                slots: [
                    {
                        target: "links",
                        id: actorData.system.heldenausruestung[setIndex]?.links,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.links)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.links)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.links")
                    },
                    {
                        target: "rechts",
                        id: actorData.system.heldenausruestung[setIndex]?.rechts,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.rechts)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.rechts)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.rechts")
                    },
                    {
                        target: "brust",
                        id: actorData.system.heldenausruestung[setIndex]?.brust,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.brust)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.brust)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.brust")
                    },
                    {
                        target: "ruecken",
                        id: actorData.system.heldenausruestung[setIndex]?.ruecken,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.ruecken)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.ruecken)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.ruecken")
                    },
                    {
                        target: "kopf",
                        id: actorData.system.heldenausruestung[setIndex]?.kopf,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.kopf)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.kopf)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.kopf")
                    },
                    {
                        target: "fernkampf",
                        id: actorData.system.heldenausruestung[setIndex]?.fernkampf,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.fernkampf)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.fernkampf)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.fernkampf")
                    },
                    {
                        target: "munition",
                        id: actorData.system.heldenausruestung[setIndex]?.munition,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.munition)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.munition)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.munition")
                    },
                    {
                        target: "armlinks",
                        id: actorData.system.heldenausruestung[setIndex]?.armlinks,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.armlinks)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.armlinks)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.armlinks")
                    },
                    {
                        target: "armrechts",
                        id: actorData.system.heldenausruestung[setIndex]?.armrechts,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.armrechts)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.armrechts)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.armrechts")
                    },
                    {
                        target: "bauch",
                        id: actorData.system.heldenausruestung[setIndex]?.bauch,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.bauch)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.bauch)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.bauch")
                    },
                    {
                        target: "beinlinks",
                        id: actorData.system.heldenausruestung[setIndex]?.beinlinks,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.beinlinks)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.beinlinks)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.beinlinks")
                    },
                    {
                        target: "beinrechts",
                        id: actorData.system.heldenausruestung[setIndex]?.beinrechts,
                        name: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.beinrechts)?.name,
                        icon: actorData.items.get(actorData.system.heldenausruestung[setIndex]?.beinrechts)?.img,
                        tooltip: game.i18n.localize("EQUIPMENT.SLOTS.beinrechts")
                    }
                ]
            })
        }
        context.selectedTab = thisObject.selectedTab ?? context.sets[0].tab
        context.setEquipped = actorData.system.setEquipped

        return context
    },
    _onRender: (context, options, thisObject) => {

        new foundry.applications.ux.DragDrop.implementation({
            dragSelector: ".inventory-table .equipment",
            dropSelector: ".tab",
            permissions: {
                dragstart: thisObject._canDragStart.bind(thisObject),
                drop: thisObject._canDragDrop.bind(thisObject)
            },
            callbacks: {
                dragstart: thisObject._onDragStart.bind(thisObject),
                drop: thisObject._onDrop.bind(thisObject),
                dragover: thisObject._onDragOver.bind(thisObject)
            }
        }).bind(thisObject.element);

        const tabs = new foundry.applications.ux.Tabs({
            navSelector: ".set .tabs.sets",
            contentSelector: ".set .tab",
            initial: thisObject.actor.system.setEquipped ? "pane" + (thisObject.actor.system.setEquipped + 1) : "pane1",
            group: "set-tabs",
            callback: (event, tab, tabName) => {
                thisObject.selectedTab = tabName
                thisObject.element.querySelectorAll(tab._contentSelector).forEach(
                    (tab) => {
                        if (tab.dataset["tab"] === tabName) {
                            tab.classList.add("active")
                        } else {
                            tab.classList.remove("active")
                        }
                    }
                )
            }
        })

        tabs.bind(thisObject.element)

        new ContextMenu(
            thisObject.element,
            ".paperdoll .equipped",
            [
                {
                    name: "Abrüsten",
                    icon: '<i class="fa-solid fa-suitcase"></i>',
                    callback: (targetElement) => {
                        const {setId, target} = targetElement.dataset
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        delete updateObject[`system.heldenausruestung.${setId}.${target}`]
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        return thisObject.document.isWorn(itemId)
                    }
                },
            ], {jQuery: false})

        new ContextMenu(
            thisObject.element,
            ".inventory-table .equipment",
            [
                {
                    name: "Abrüsten",
                    icon: '<i class="fa-solid fa-suitcase"></i>',
                    callback: (target) => {
                        const {itemId} = target.dataset
                        const itemSlot = thisObject.document.isWorn(itemId)
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        delete updateObject[`system.heldenausruestung.${thisObject.document.system.setEquipped}.${itemSlot}`]
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const itemIsWorn = thisObject.document.isWorn(itemId)
                        return itemIsWorn
                    }
                },
                {
                    name: "Ausrüsten (Munition)",

                    callback: (target) => {
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        updateObject[`system.heldenausruestung.${thisObject.document.system.setEquipped}.munition`] = target.dataset.itemId
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return !thisObject.document.isWorn(itemId) && item.system.category.indexOf("Munition") != -1
                    }
                },
                {
                    name: "Ausrüsten",
                    callback: (target) => {
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        // find next unoccupied slot and enter the item
                        const nextUnoccupiedSlot = Object.entries(updateObject).find(([key, value]) => {
                            // but not when it is a weapon slot
                            return value === null
                                && key.indexOf(".links") === -1
                                && key.indexOf(".rechts") === -1
                                && key.indexOf(".fernkampf") === -1
                                && key.indexOf(".Munition") === -1
                        })
                        updateObject[nextUnoccupiedSlot[0]] = target.dataset.itemId
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return !thisObject.document.isWorn(itemId) && item.system.category.indexOf("Rüstung") != -1
                    }
                },
                {
                    name: "Ausrüsten (Rechte Hand)",
                    callback: (target) => {
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        updateObject[`system.heldenausruestung.${thisObject.document.system.setEquipped}.rechts`] = target.dataset.itemId
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return !thisObject.document.isWorn(itemId) && item.system.category.indexOf("Nahkampfwaffe") != -1
                    }
                },
                {
                    name: "Ausrüsten (Linke Hand)",
                    callback: (target) => {
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        updateObject[`system.heldenausruestung.${thisObject.document.system.setEquipped}.links`] = target.dataset.itemId
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return !thisObject.document.isWorn(itemId) && item.system.category.indexOf("Nahkampfwaffe") != -1
                    }
                },
                {
                    name: "Ausrüsten (Fernkampf)",
                    callback: (target) => {
                        const updateObject = thisObject.document.getEquipmentSetUpdateObject()
                        updateObject[`system.heldenausruestung.${thisObject.document.system.setEquipped}.fernkampf`] = target.dataset.itemId
                        thisObject.document.update(updateObject)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return !thisObject.document.isWorn(itemId) && item.system.category.indexOf("Fernkampfwaffe") != -1
                    }
                },
                {
                    name: "Aufteilen",
                    icon: '<i class="fa-solid fa-split"></i>',
                    callback: async (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        const previousStackSize = item.system.quantity
                        const newStackSize = await foundry.applications.api.DialogV2.prompt({
                            window: {title: "Größe des neuen Stapels"},
                            content: `<input name="size" type="number" min="1" max="${previousStackSize}" value="1" step="1" autofocus>`,
                            ok: {
                                label: "Aufteilen",
                                callback: (event, button, dialog) => button.form.elements.size.valueAsNumber
                            }
                        });
                        if (newStackSize) {
                            const clone = item.clone({
                                system: {
                                    quantity: newStackSize
                                }
                            })
                            thisObject.document.createEmbeddedDocuments('Item', [clone])
                            item.update({"system.quantity": previousStackSize - newStackSize})
                        }
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        const item = thisObject.document.items.get(itemId)
                        return item.system.quantity > 1
                    }
                },
                {
                    name: "Aus dem Inventar entfernen",
                    icon: '<i class="fa-solid fa-trash"></i>',
                    callback: (target) => {
                        game.DSA41.socket.executeAsGM("removeFromLootTable", thisObject.document.id, target.dataset.itemId)
                    },
                    condition: (target) => {
                        const {itemId} = target.dataset
                        return !thisObject.document.isWorn(itemId)
                    }
                }
            ], {jQuery: false});
    },
    _getTabConfig: (group) => {
        group?.tabs.push({id: "equipment", group: "sheet", label: "Ausrüstung"})
    },
    template: `systems/DSA_4-1/templates/actor/character/tab-equipment.hbs`
}