import { onUnmounted, ref } from "vue"
import { clone } from "ramda"
import getStateObservable from "@racletteCore/lib/observableHelpers/getStateObservable"
import { $store } from "@racletteCore"
const useStateSubscriber = <T = any>(
  statePath: string | string[],
  callback?: Function,
  addOnUnmountedHook = true,
) => {
  const data = ref<T>(null)

  const subscriber$ = getStateObservable(statePath).subscribe((val) => {
    if (!$store.hasChanges(data.value, val)) {
      return
    }
    const oldValue = clone(data.value)

    data.value = val
    if (typeof callback === "function") {
      callback(val, oldValue)
    }
  })

  if (addOnUnmountedHook) {
    onUnmounted(() => subscriber$?.unsubscribe())
  }

  // expose managed state as return value
  return { subscriber$, state: data }
}

export default useStateSubscriber
export { useStateSubscriber }
