/*
Copyright 2024 New Vector Ltd.
Copyright 2021 The Matrix.org Foundation C.I.C.

SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/

import SettingController from "./SettingController";
import { type SettingLevel } from "../SettingLevel";
import { type SettingKey, type Settings } from "../Settings.tsx";
import PlatformPeg from "../../PlatformPeg.ts";

/**
 * Enforces that a boolean setting cannot be enabled if the incompatible setting
 * is also enabled, to prevent cascading undefined behaviour between conflicting
 * labs flags.
 */
export default class IncompatibleController<
    ControlledSetting extends SettingKey,
    WatchedSetting extends SettingKey,
> extends SettingController {
    public constructor(
        private settingName: WatchedSetting,
        private forcedValue: Settings[ControlledSetting]["default"] = false,
        private incompatibleValue:
            | Settings[WatchedSetting]["default"]
            | ((v: Settings[WatchedSetting]["default"]) => boolean) = true,
        private readonly disabledMessage?: string,
        private readonly forceReload = false,
    ) {
        super();
    }

    public getValueOverride(
        level: SettingLevel,
        roomId: string,
        calculatedValue: any,
        calculatedAtLevel: SettingLevel | null,
    ): any {
        if (this.incompatibleSetting) {
            return this.forcedValue;
        }
        return null; // no override
    }

    public get settingDisabled(): boolean | string {
        if (this.incompatibleSetting) {
            return this.disabledMessage ?? true;
        }
        return false;
    }

    public get incompatibleSetting(): boolean {
        if (typeof this.incompatibleValue === "function") {
            return this.incompatibleValue(this.settingsStore.getValue(this.settingName));
        }
        return this.settingsStore.getValue(this.settingName) === this.incompatibleValue;
    }

    public onChange(): void {
        if (this.forceReload) {
            PlatformPeg.get()?.reload();
        }
    }
}
