import { PrimariaBroker } from "../broker/primaria-broker";

export abstract class PrimariaGlobalStateManager {
  abstract setData<T>(key: string, value: T): void;
  abstract getData<T>(key: string): T | undefined;
  abstract clearData(): void;
}

class PrimariaGlobalStateManagerImpl implements PrimariaGlobalStateManager {
  private state: { [key: string]: unknown } = {};
  constructor(public broker: PrimariaBroker) {}

  /**
   * Sets the value of a key in the state object and publishes an event with the event bus.
   *
   * @param {string} key - The key to set the value for.
   * @param {T} value - The value to set for the key.
   * @return {void} This function does not return anything.
   */
  setData<T>(key: string, value: T): void {
    this.state[key] = value;
    this.broker.publish("data_set", {
      key: key,
      value: value,
    });
  }

  /**
   * Retrieves the value associated with the specified key from the state object.
   *
   * @param {string} key - The key to retrieve the value for.
   * @return {T | undefined} The value associated with the specified key, or undefined if the key does not exist in the state object.
   */
  getData<T>(key: string): T | undefined {
    return this.state[key] as T | undefined;
  }

  /**
   * Clears all data stored in the state object.
   *
   * @return {void} This function does not return anything.
   */
  public clearData(): void {
    this.state = {};
  }
}

export const createGlobalStateManager = (broker: PrimariaBroker) =>
  new PrimariaGlobalStateManagerImpl(broker);
