import { SettingKey } from '@util/settings.ts';

export class DynamicSettings {
  private settings: { [k: string]: string | null };
  private changedSettings: { [k: string]: string | null } = {};

  constructor(settings: typeof this.settings) {
    this.settings = settings;
  }

  private get<V extends string | boolean>(key: string, defaultValue: V): V {
    const setting = this.changedSettings[key] ?? this.settings[key];
    return setting != null ? JSON.parse(setting) : defaultValue;
  }

  private set<V extends string | boolean>(key: string, value: V | null) {
    if (this.settings[key] == value) {
      delete this.changedSettings[key];
    } else {
      this.changedSettings[key] = value != null ? JSON.stringify(value) : null;
    }
  }

  getChanges() {
    return this.changedSettings;
  }

  setChanges() {
    this.settings = Object.assign(this.settings, this.changedSettings);
    this.changedSettings = {};
  }

  /* signup enabled */
  signupEnabled = () => this.get(SettingKey.SignupEnabled, false);
  signupSetEnabled = (enabled: boolean) => this.set(SettingKey.SignupEnabled, enabled);

  /* signup info text */
  signupInfoText = () => this.get(SettingKey.SignupInfoMessage, '');
  signupSetInfoText = (text: string) => this.set(SettingKey.SignupInfoMessage, text);

  /* signup disabled text */
  signupDisabledText = () => this.get(SettingKey.SignupDisabledMessage, '');
  signupSetDisabledText = (text: string) => this.set(SettingKey.SignupDisabledMessage, text);

  /* signup disabled subtext */
  signupDisabledSubtext = () => this.get(SettingKey.SignupDisabledSubMessage, '');
  signupSetDisabledSubtext = (text: string) => this.set(SettingKey.SignupDisabledSubMessage, text);

  /* live statistics enabled */
  liveStatisticsEnabled = () => this.get(SettingKey.LiveStatisticsEnabled, false);
  liveStatisticsSetEnabled = (enabled: boolean) => this.set(SettingKey.LiveStatisticsEnabled, enabled);
}
