import { DataTableFilterMeta } from "primereact/datatable";
import { useContext, useEffect } from "react";
import { OSDataTableContext } from "../OSDataTable";

/**
 * Attempts to initialize filter if not present on provider.
 * @param filter
 */
export function useFilterAutoInit(filter: string) {
  const tableContext = useContext(OSDataTableContext);

  //Add filter to filters object if not present.
  useEffect(() => {
    if (!filter || !tableContext) return;

    const currentFilters = tableContext.filters ?? {};
    const newFilters =
      filter in currentFilters
        ? currentFilters
        : ({
            ...currentFilters,
            [filter]: { value: null, matchMode: "startsWith" },
          } as DataTableFilterMeta);

    tableContext.setFilters?.(newFilters);
  }, [filter]);
}
