import React from 'react';
import { useStoreInstance } from '../store-context';
import {
  DefaultShapeData,
  ShapeConfig,
  StoreSelector,
  StoreValue,
} from '../types';

export function useAnnotatorStore<ReturnType>(
  selector: StoreSelector<ReturnType> = (internalStore: StoreValue) =>
    internalStore as ReturnType,
) {
  const store = useStoreInstance();
  return React.useSyncExternalStore(store.subscribe, () =>
    selector(store.getStore()),
  );
}

export function useShapes<TData = DefaultShapeData>() {
  // @ts-ignore
  return useAnnotatorStore<ShapeConfig<TData>[]>((store) => store.shapes);
}

export function useSelectedShapeId() {
  return useAnnotatorStore((store) => store.selectedShapeId);
}

export function useBackground(): string {
  return useAnnotatorStore((store) => store.background);
}
