export class GroupSheet extends ActorSheet {
    /**@override */
    static get defaultOptions() {
        return foundry.utils.mergeObject(super.defaultOptions, {
            classes: ['dsa41', 'sheet', 'actor', 'group'],
            width: 520,
            height: 480,
            tabs: [
                {
                    navSelector: '.sheet-tabs',
                    contentSelector: '.sheet-body',
                    initial: 'description',
                },
            ],
        });
    }

    /** @override */
    async getData() {
        const context = super.getData();

        // Use a safe clone of the actor data for further operations.
        const groupData = context.data;

        // Add the actor's data to context.data for easier access, as well as flags.
        context.system = groupData.system;
        context.flags = groupData.flags;

        context.characters = [];

        for (const characterId of groupData.system.characters) {
            const character = await game.actors.get(characterId)
            context.characters.push(
                {
                    img: character.img,
                    name: character.name,
                    id: character._id,
                    attributes: [
                        {name: "MU", value: character.system.attribute.mu.aktuell},
                        {name: "KL", value: character.system.attribute.kl.aktuell},
                        {name: "IN", value: character.system.attribute.in.aktuell},
                        {name: "CH", value: character.system.attribute.ch.aktuell},
                        {name: "FF", value: character.system.attribute.ff.aktuell},
                        {name: "GE", value: character.system.attribute.ge.aktuell},
                        {name: "KO", value: character.system.attribute.ko.aktuell},
                        {name: "KK", value: character.system.attribute.kk.aktuell},
                    ],
                    advantages: character.items.filter((i) => i.type === "Advantage").map((advantage) => {
                        return {
                            name: advantage.name,
                            id: advantage._id,
                            value: advantage.system.value,
                        }
                    }),
                    skills: character.items.filter((i) => i.type === "Skill").map((skill) => {
                        return {
                            name: skill.name,
                            taw: skill.system.taw,
                            id: skill._id
                        }
                    }),
                    isLimited: character.isOwner || !character.limited,
                    isVisible: character.isOwner || character.visible,
                    isOwner: character.isOwner
                }
            )
        }


        context.equipments = [];
        const actorData = context.data;
        Object.values(actorData.items).forEach((item, index) => {
            if (item.type === "Equipment") {
                context.equipments.push({
                    index: index,
                    id: item._id,
                    quantity: item.system.quantity,
                    name: item.name,
                    icon: item.img
                })
            }
        })

        return await context;
    }

    /** @override */
    get template() {
        return `systems/DSA_4-1/templates/actor/group-sheet.hbs`;
    }

    static async onDroppedData(group, sheet, data) {
        if (data.type === "Actor") {
            const uuid = await foundry.utils.parseUuid(data.uuid);
            const character = await (game.actors.get(uuid.id))
            // check if character already is part of the group
            if (group.system.characters.includes(character._id)) {
                ui.notifications.warn(`${character.name} befindet sich bereits in der Heldengruppe ${group.name}`)
                return false;
            }


            // update group
            await group.update({
                system: {
                    characters: [
                        ...group.system.characters,
                        character._id
                    ]
                }
            })
            ui.notifications.info(`${character.name} ist der Heldengruppe ${group.name} beigetreten`)
        }
        if (data.type === "Equipment") {
            const uuid = await foundry.utils.parseUuid(data.uuid);
            const equipment = await (game.actors.get(uuid.id))
            ui.notifications.info(`${equipment.name} befindet sich nun im Inventar der Heldengruppe ${group.name}`)
            return true;
        }
    }

    openEmbeddedDocument(documentId) {
        this.object.items.get(documentId).sheet.render(true)
    }

    activateListeners(html) {
        super.activateListeners(html);

        html.on('click', '.owneroption.clickable', async (evt) => {
            const dataset = evt.target.dataset;
            const group = this.object;
            switch (dataset.operation) {
                case "removeFromParty":
                    const charactersWithoutMember = group.system.characters.filter(id => id !== dataset.id)
                    await group.update({
                        system: {
                            characters: charactersWithoutMember
                        }
                    })
            }
        });
        html.on('click', '.header.clickable', async (evt) => {
            const {id, operation} = evt.currentTarget.dataset;
            if (operation === "openActorSheet") {
                evt.stopPropagation();
                (await game.actors.get(id)).sheet.render(true);
            }
        })


        html.on('click', '.equipment', (evt) => {
            this.openEmbeddedDocument(evt.target.dataset.id);
            evt.stopPropagation();
        })

        new ContextMenu(html, '.equipment', [
            {
                name: "Aus dem Gruppeninventar entfernen",
                icon: '<i class="fa-solid fa-trash"></i>',
                callback: (event) => {
                    this.object.deleteEmbeddedDocuments('Item', [event[0].dataset.id])
                },
                condition: () => true
            }
        ]);
    }
}
