import type { ComputedRef } from 'vue';

import type { BasicTableProps } from '../types/table';

import { computed, ref, unref, watch } from 'vue';

export function useLoading(props: ComputedRef<BasicTableProps>) {
  const loadingRef = ref(unref(props).loading);
  const loadingTipRef = ref(unref(props).loadingTip);

  watch(
    () => [unref(props).loading, unref(props).loadingTip] as const,
    ([loading, loadingTip]) => {
      loadingRef.value = loading;
      loadingTipRef.value = loadingTip;
    },
  );

  const getLoading = computed(() => unref(loadingRef));
  const getLoadingTip = computed(() => unref(loadingTipRef));

  function setLoading(loading: boolean, tip?: string) {
    loadingRef.value = loading;
    loadingTipRef.value = loading ? tip : undefined;
  }

  return { getLoading, getLoadingTip, setLoading };
}
