import {
  inject,
  provide,
  ref,
  watch
} from "vue";
import {
  CRUD_KEY,
  CRUD_OPTIONS_KEY,
  IMPORT_OPTIONS_KEY,
  SEARCH_OPTIONS_KEY,
  TABLE_OPTIONS_KEY,
  UPSERT_OPTIONS_KEY
} from "./key";
import { applyTablePlugins } from "./plugins";
export function useCrud(options, cb) {
  if (!options) {
    const ctx = inject(CRUD_KEY);
    if (!ctx)
      throw new Error("[useCrud] 必须在 VmCrud 内使用");
    return ctx;
  }
  provide(CRUD_OPTIONS_KEY, options);
  const Crud = ref();
  watch(Crud, (val) => {
    if (val && cb)
      cb(val);
  }, { immediate: true });
  return Crud;
}
export function useTable(options, cb) {
  const Table = ref();
  if (options)
    provide(TABLE_OPTIONS_KEY, applyTablePlugins(options));
  watch(Table, (val) => {
    if (val && cb)
      cb(val);
  });
  return Table;
}
export function useUpsert(options) {
  const Upsert = ref();
  if (options)
    provide(UPSERT_OPTIONS_KEY, options);
  return Upsert;
}
export function useSearch(options) {
  const Search = ref();
  if (options)
    provide(SEARCH_OPTIONS_KEY, options);
  return Search;
}
export function useImport(options) {
  if (options)
    provide(IMPORT_OPTIONS_KEY, options);
}
export function useCore() {
  const crud = inject(CRUD_KEY);
  if (!crud)
    throw new Error("[useCore] 必须在 VmCrud 内使用");
  return { crud };
}

export { CRUD_KEY };
