import { useEnvironment, QueryLanguage } from "@contember/binding";
import { useSessionStorageState } from "@contember/react-utils";
import { useMemo } from "react";
import { collectFilters } from "../grid/collectFilters.js";
import { collectOrderBy } from "../grid/collectOrderBy.js";
import { useFilters } from "../grid/useFilters.js";
import { useHiddenColumnsState } from "../grid/useHiddenColumnsState.js";
import { useOrderBys } from "../grid/useOrderBys.js";
import { useDataGridKey } from "./useDataGridKey.js";
import { extractDataGridColumns } from "../structure/gridTemplateAnalyzer.js";
import { useGridPagingState } from "../paging/useGridPagingState.js";
const useDataGridState = (props) => {
  const dataGridKey = useDataGridKey(props);
  const environment = useEnvironment();
  const columns = useMemo(() => extractDataGridColumns(props.children), [props.children]);
  const [pageState, updatePaging] = useGridPagingState(props.itemsPerPage ?? null, dataGridKey);
  const [hiddenColumns, setIsColumnHidden] = useHiddenColumnsState(columns, dataGridKey);
  const [orderDirections, setOrderBy] = useOrderBys(columns, updatePaging, dataGridKey);
  const [filterArtifacts, setFilter] = useFilters(columns, updatePaging, dataGridKey);
  const entities = useMemo(() => QueryLanguage.desugarQualifiedEntityList({ entities: props.entities }, environment), [environment, props.entities]);
  const [layout, setLayout] = useSessionStorageState(`${dataGridKey}-layout`, (layout2) => layout2 ?? (props.tile ? "tiles" : "default"));
  const desiredState = useMemo(() => {
    const columnFilters = collectFilters(columns, filterArtifacts, environment);
    const filter = { and: [...columnFilters, entities.filter ?? {}] };
    const orderBy = collectOrderBy(columns, orderDirections, environment);
    return {
      paging: pageState,
      columns,
      hiddenColumns,
      filterArtifacts,
      orderDirections,
      entities,
      filter,
      layout,
      orderBy
    };
  }, [columns, filterArtifacts, environment, entities, pageState, hiddenColumns, orderDirections, layout]);
  return [
    desiredState,
    useMemo(() => ({ updatePaging, setFilter, setIsColumnHidden, setOrderBy, setLayout }), [updatePaging, setFilter, setIsColumnHidden, setOrderBy, setLayout])
  ];
};
export { useDataGridState };
//# sourceMappingURL=useDataGridState.js.map
