import { DS4Item } from "./item";
import { DS4ItemDataType } from "./item-data";

/**
 * Extend the basic ItemSheet with some very simple modifications
 * @extends {ItemSheet}
 */
export class DS4ItemSheet extends ItemSheet<DS4ItemDataType, DS4Item> {
    /** @override */
    static get defaultOptions(): FormApplicationOptions {
        return mergeObject(super.defaultOptions, {
            width: 530,
            height: 400,
            classes: ["ds4", "sheet", "item"],
            tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "description" }],
        });
    }

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

    /* -------------------------------------------- */

    /** @override */
    getData(): ItemSheetData<DS4ItemDataType, DS4Item> {
        const data = { ...super.getData(), config: CONFIG.DS4 };
        console.log(data);
        return data;
    }

    /* -------------------------------------------- */

    /** @override */
    setPosition(options: ApplicationPosition = {}): ApplicationPosition {
        const position = super.setPosition(options);
        if ("find" in this.element) {
            const sheetBody = this.element.find(".sheet-body");
            const bodyHeight = position.height - 192;
            sheetBody.css("height", bodyHeight);
        } else {
            console.log("Failure setting position.");
        }
        return position;
    }

    /* -------------------------------------------- */

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

        if (!this.options.editable) return;

        html.find(".effect-create").on("click", this._onEffectCreate.bind(this));

        html.find(".effect-edit").on("click", (ev) => {
            const li = $(ev.currentTarget).parents(".effect");
            console.log(li.data("effectId"));
            const effect = this.item.effects.get(li.data("effectId"));
            effect.sheet.render(true);
        });

        html.find(".effect-delete").on("click", async (ev) => {
            const li = $(ev.currentTarget).parents(".effect");
            await this.item.deleteEmbeddedEntity("ActiveEffect", li.data("effectId"));
        });
    }

    /**
     * Handle creating a new ActiveEffect for the item using initial data defined in the HTML dataset
     * @param {Event} event   The originating click event
     * @private
     */
    private async _onEffectCreate(event: JQuery.ClickEvent): Promise<unknown> {
        event.preventDefault();

        const label = `New Effect`;

        const createData = {
            label: label,
            changes: [],
            duration: {},
            transfer: true,
        };

        const effect = await ActiveEffect.create(createData, this.item);
        return effect.create({});
    }
}