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

export class ConditionEvaluator {
    constructor() {
        this.conditions = {};
    }

    get playlist() {
        return game.playlists.get(game.settings.get(MODULE_ID, "playingPlaylist"));
    }

    setHooks() {
        if(game.user !== game.users.activeGM) return;
        Hooks.on("combatStart", () => {
            Hooks.once("updateCombat", () => this._onConditionChanged());
        });
        Hooks.on("deleteCombat", () => this._onConditionChanged());
        Hooks.on("updateScene", () => this._onConditionChanged());
        Hooks.on("updatePlaylist", () => this._onConditionChanged());
    }

    _onConditionChanged() {
        if (ui.dynamicSoundscapes?.rendered) ui.dynamicSoundscapes.debouncedRefresh();
        else ui.dynamicSoundscapes.updateState();
    }

    evaluateCondition(block) {
        const conditions = block.conditions ?? [];
        const mode = block.conditionMode ?? "all";
        if (!conditions?.length) return true;
        switch (mode) {
            case "all":
                return conditions.every((condition) => this.isConditionMet(condition));
            case "any":
                return conditions.some((condition) => this.isConditionMet(condition));
            case "none":
                return conditions.every((condition) => !this.isConditionMet(condition));
            default:
                return conditions.every((condition) => this.isConditionMet(condition));
        }
    }

    isConditionMet(condition) {
        const isWeather = condition.startsWith("weather-");
        const conditionFunction = isWeather ? this.isWeather.bind(this) : this[condition].bind(this);
        return conditionFunction(condition);
    }

    //---------------Conditions-------------------//

    isWeather(condition) {
        const weatherKey = condition.replace("weather-fxmaster.", "").replace("weather-", "");
        if (canvas.scene.weather == weatherKey) return true;
        if (Object.values(canvas.scene?.flags?.fxmaster?.effects ?? {}).some((e) => e.type === weatherKey)) return true;
        return false;
    }

    inCombat() {
        return game.combat?.started;
    }

    notInCombat() {
        return !game.combat?.started;
    }

    day() {
        return game.scenes.active?._source.environment.darknessLevel < 0.5;
    }

    night() {
        return game.scenes.active?._source.environment.darknessLevel >= 0.5;
    }

    moodA() {
        const flag = this.playlist?.getFlag(MODULE_ID, "mood");
        return flag === "moodA" || !flag;
    }

    moodB() {
        return this.playlist?.getFlag(MODULE_ID, "mood") === "moodB";
    }

    moodC() {
        return this.playlist?.getFlag(MODULE_ID, "mood") === "moodC";
    }

    //--------------------------------------------//
}
