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

export interface ISimplePageContentLoader<T, P> extends ILoaderCommon<P> {
  content: Ref<T|null>;
}

export function useSimplePageContentLoader<T, P = any>(
  loader: (params?: P) => Promise<T>
)  : ISimplePageContentLoader<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';
    try {
      const res = (await loader(params ?? lastParams)) as T;
      content.value = res;
      loadStatus.value = 'finished';
      loadError.value = '';
    } catch(e) {
      loadError.value = '' + e;
      loadStatus.value = 'error';
    }
  }

  return {
    content,
    loadStatus,
    loadError,
    loadData,
  }
}