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


const SELECT_OPTIONS = {
    size: {
        "40px": "dynamic-soundscapes.block-config.size-tiny",
        "50px": "dynamic-soundscapes.block-config.size-small",
        "60px": "dynamic-soundscapes.block-config.size-medium",
        "70px": "dynamic-soundscapes.block-config.size-large",
        "90px": "dynamic-soundscapes.block-config.size-huge",
    },
    conditionMode: {
        "all": "dynamic-soundscapes.block-config.conditionMode-all",
        "any": "dynamic-soundscapes.block-config.conditionMode-any",
        "none": "dynamic-soundscapes.block-config.conditionMode-none",
    },
    mode: {
        "soundboard": "dynamic-soundscapes.block-config.mode-soundboard",
        "ambient": "dynamic-soundscapes.block-config.mode-ambient",
        "random": "dynamic-soundscapes.block-config.mode-random",
    },
    conditionPicker: {
        "": "dynamic-soundscapes.block-config.conditions-none",
        "inCombat": "dynamic-soundscapes.block-config.conditions-inCombat",
        "notInCombat": "dynamic-soundscapes.block-config.conditions-notInCombat",
        "day": "dynamic-soundscapes.block-config.conditions-day",
        "night": "dynamic-soundscapes.block-config.conditions-night",
        "moodA": "dynamic-soundscapes.block-config.conditions-moodA",
        "moodB": "dynamic-soundscapes.block-config.conditions-moodB",
        "moodC": "dynamic-soundscapes.block-config.conditions-moodC",
        // Weather effects will be dynamically added in the `getData` method.
    },
}


let weatherEffectsAdded = false;



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 = Object.entries(CONFIG.weatherEffects).reduce((types, [key, value]) => {
          types[key] = game.i18n.localize(value.label);
          return types;
        }, {});
        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,
                });
            }
        }

        if (!weatherEffectsAdded) {
            weatherEffectsAdded = true;
            SELECT_OPTIONS.conditionPicker = {
                ...SELECT_OPTIONS.conditionPicker,
                ...weatherEffects,
            };
        }

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

    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(`[name="mode"]`).addEventListener("change", (e) => {
            const timeFg = html.querySelector(`[name="time"]`).closest(".form-group");
            const varianceFg = html.querySelector(`[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(`[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();
    }
}
