import { useSyncEffect } from "@tingwujs/common";
import { SphereController } from "../../base";
import useForceUpdate from "use-force-update";

export const useSphereState = <
  S extends Record<string, any>,
  E extends Record<string, any>,
  K extends keyof S,
>(
  controller: SphereController<S, E> | undefined,
  stateKey: K
): S[K] | undefined => {
  const value = controller?.getState(stateKey);

  const forceUpdate = useForceUpdate();
  useSyncEffect(() => {
    if (!controller) {
      return;
    }
    return controller.onStateChange(event => {
      const { key } = event;
      if (key === stateKey) {
        forceUpdate();
      }
    });
  }, [controller, stateKey, forceUpdate]);
  return value;
};
