import { MODULE_ID } from "../main.js";

export class BlockConfig extends FormApplication {
    constructor(playlist, blockId) {
        super();
        this.playlist = playlist;
        this.blockId = blockId;
        this.block = this.playlist.getFlag(MODULE_ID, "blocks").find((b) => b.id === this.blockId);
        this.block = JSON.parse(JSON.stringify(this.block));
        this._conditions = this.block.conditions ?? [];
    }

    getData() {
        const weatherEffects = {};
        const coreWeatherEffects = SceneConfig.prototype._getWeatherTypes();
        for (const [key, value] of Object.entries(coreWeatherEffects)) {
            weatherEffects["weather-"+key] = game.i18n.localize(`${MODULE_ID}.block-config.coreWeather`) + value;
        }

        const conditions = [];
        for (const condition of this._conditions) {
            if (condition.startsWith("weather-")) {
                conditions.push({
                    name: weatherEffects[condition],
                    condition: condition,
                });
            }
            else {
                conditions.push({
                    name: game.i18n.localize(`${MODULE_ID}.block-config.conditions-` + condition),
                    condition: condition,
                });
            }
        }

        return {
            ...this.block,
            conditions: conditions,
            weatherEffects: weatherEffects,
        };
    }

    static get defaultOptions() {
        return {
            ...super.defaultOptions,
            id: "soundscapes-block-config",
            classes: ["soundscapes-block-config"],
            template: `modules/dynamic-soundscapes/templates/block-config.hbs`,
            title: game.i18n.localize(`${MODULE_ID}.block-config.title`),
            resizable: false,
            popOut: true,
            width: 400,
        };
    }

    activateListeners(html) {
        super.activateListeners(html);
        this.setTimeText();
        html = html[0];
        html.querySelectorAll("input").forEach((i) => i.addEventListener("change", () => this.setTimeText()));
        html.querySelector(`select[name="mode"]`).addEventListener("change", (e) => {
            const timeFg = html.querySelector(`input[name="time"]`).closest(".form-group");
            const varianceFg = html.querySelector(`input[name="variance"]`).closest(".form-group");
            if (e.target.value === "random") {
                timeFg.style.display = "flex";
                varianceFg.style.display = "flex";
            } else {
                timeFg.style.display = "none";
                varianceFg.style.display = "none";
            }
            this.setPosition({ height: "auto", width: 400});
        });
        html.querySelector('#condition-picker').addEventListener("change", async (e) => {
            if(!e.target.value) return;
            const value = e.target.value;
            e.target.value = "";
            if(this._conditions.includes(value)) return;
            this._conditions.push(value);      
            this.updateData();
            this.render(true);
        });
        html.querySelectorAll(".delete-condition").forEach((el) => el.addEventListener("click", (e) => {
            const condition = e.target.closest(".soundscapes-condition").dataset.condition;
            this._conditions = this._conditions.filter((c) => c !== condition);
            this.updateData();
            this.render(true);
        }));
        html.querySelector(`select[name="mode"]`).dispatchEvent(new Event("change"));
    }

    setTimeText() {
        const pEl = this.element[0].querySelector("#time-text");
        const time = parseInt(this._getSubmitData().time);
        const variance = parseFloat(this._getSubmitData().variance);
        const varianceText = `${parseInt(time - time * variance)} - ${parseInt(time + time * variance)}`;
        pEl.innerText = game.i18n.localize(`${MODULE_ID}.block-config.time-text`).replace("{{v}}", varianceText);
        this.setPosition({ height: "auto", width: 400});
    }

    updateData() {
        this.block = {
            ...this.block,
            ...this._getSubmitData(),
            conditions: this._conditions,
        };
    }

    async _onSubmit(event) {
        event.preventDefault();
        const newBlockData = {
            ...this.block,
            ...this._getSubmitData(),
            conditions: this._conditions,
        };
        const oldBlocks = this.playlist.getFlag(MODULE_ID, "blocks");
        const newBlocks = oldBlocks.map((b) => (b.id === this.blockId ? newBlockData : b));
        await this.playlist.setFlag(MODULE_ID, "blocks", newBlocks);
        Object.values(ui.windows)
            .filter((w) => w.id == "soundscapes")
            .forEach((w) => w.render(true));
        this.close();
    }
}
