import { onMounted, ref, type Ref } from "vue";
import type { ILoaderCommon, LoaderLoadType } from "./LoaderCommon";
import { formatError } from "./ErrorDisplay";

export interface ISimpleDataLoader<T, P> extends ILoaderCommon<P> {
  content: Ref<T|null>;
  getLastParams: () => P | undefined;
}

export function useSimpleDataLoader<T, P = any>(
  loader: (params?: P) => Promise<T>,
  loadWhenMounted = true,
  emptyIfArrayEmpty = true,
  showGlobalLoading = false,
)  : ISimpleDataLoader<T, P>
 {

  const content = ref<T|null>(null) as Ref<T|null>;
  const loadStatus = ref<LoaderLoadType>('loading');
  const loadError = ref('');

  let lastParams: P | undefined;

  async function loadData(params?: P) {
    if (params)
      lastParams = params;
    loadStatus.value = 'loading';
    if (showGlobalLoading)
      uni.showLoading({ title: '加载中...' });

    try {
      const res = (await loader(params ?? lastParams)) as T;
      content.value = res;
      if (Array.isArray(res) && emptyIfArrayEmpty && (res as any[]).length === 0)
        loadStatus.value = 'nomore';
      else
        loadStatus.value = 'finished';
      loadError.value = '';
    } catch(e) {
      loadError.value = formatError(e);
      loadStatus.value = 'error';
      console.error(e);
    } finally {
      if (showGlobalLoading)
        uni.hideLoading();
    }
  }

  if (loadWhenMounted) {
    onMounted(() => {
        setTimeout(() => {
          loadData();
        }, (0.5 + Math.random()) * 500);
    })
  }

  return {
    content,
    loadStatus,
    loadError,
    loadData,
    getLastParams: () => lastParams,
  }
}