// SPDX-FileCopyrightText: 2021 Johannes Loher
// SPDX-FileCopyrightText: 2021 Oliver Rümpelein
// SPDX-FileCopyrightText: 2021 Gesina Schwalbe
//
// SPDX-License-Identifier: MIT

import { DS4 } from "../config";
import { getGame } from "../helpers";
import notifications from "../ui/notifications";
import { isDS4ItemDataTypePhysical } from "./item-data-source";

/**
 * The Sheet class for DS4 Items
 */
export class DS4ItemSheet extends ItemSheet<ItemSheet.Options, DS4ItemSheetData> {
    /** @override */
    static get defaultOptions(): ItemSheet.Options {
        return foundry.utils.mergeObject(super.defaultOptions, {
            width: 540,
            height: 400,
            classes: ["ds4", "sheet", "item"],
            tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "description" }],
            scrollY: [".tab.description", ".tab.effects", ".tab.details"],
        });
    }

    /** @override */
    get template(): string {
        const basePath = "systems/ds4/templates/sheets/item";
        return `${basePath}/${this.item.data.type}-sheet.hbs`;
    }

    /** @override */
    async getData(): Promise<DS4ItemSheetData> {
        const data = {
            ...(await super.getData()),
            config: DS4,
            isOwned: this.item.isOwned,
            actor: this.item.actor,
            isPhysical: isDS4ItemDataTypePhysical(this.item.data.data),
        };
        return data;
    }

    /** @override */
    setPosition(options: Partial<Application.Position> = {}): (Application.Position & { height: number }) | undefined {
        const position = super.setPosition(options);
        if (position) {
            const sheetBody = this.element.find(".sheet-body");
            const bodyHeight = position.height - 192;
            sheetBody.css("height", bodyHeight);
        }

        return position;
    }

    /** @override */
    activateListeners(html: JQuery): void {
        super.activateListeners(html);

        if (!this.options.editable) return;

        html.find(".effect-control").on("click", this._onManageActiveEffect.bind(this));
    }

    /**
     * Handle management of ActiveEffects.
     * @param event - he originating click event
     */
    protected async _onManageActiveEffect(event: JQuery.ClickEvent): Promise<unknown> {
        event.preventDefault();

        if (this.item.isOwned) {
            return notifications.warn(getGame().i18n.localize("DS4.WarningManageActiveEffectOnOwnedItem"));
        }
        const a = event.currentTarget;
        const li = $(a).parents(".effect");

        switch (a.dataset["action"]) {
            case "create":
                return this.createActiveEffect();
            case "edit":
                const id = li.data("effectId");
                const effect = this.item.effects.get(id);
                if (!effect) {
                    throw new Error(
                        getGame().i18n.format("DS4.ErrorItemDoesNotHaveEffect", { id, item: this.item.name }),
                    );
                }
                return effect.sheet.render(true);
            case "delete": {
                return this.item.deleteEmbeddedDocuments("ActiveEffect", [li.data("effectId")]);
            }
        }
    }

    /**
     * Create a new ActiveEffect for the item using default data.
     */
    protected async createActiveEffect(): Promise<ActiveEffect | undefined> {
        const createData = {
            label: "New Effect",
            icon: "icons/svg/aura.svg",
        };

        return ActiveEffect.create(createData, { parent: this.item });
    }
}

interface DS4ItemSheetData extends ItemSheet.Data<ItemSheet.Options> {
    config: typeof DS4;
    isOwned: boolean;
    actor: DS4ItemSheet["item"]["actor"];
    isPhysical: boolean;
}