import { createSelector } from '@ngrx/store';
import { selectShelfState } from '../shelf.selectors';
import { searchStateAdapter } from './search.state';
import { Dictionary } from '@ngrx/entity';
import { SearchProcess, SearchProcessState } from './defs';

export const selectSearchState = createSelector(selectShelfState, (s) => s.search);

export const { selectAll, selectEntities } = searchStateAdapter.getSelectors(selectSearchState);

export const selectProcess = createSelector(selectEntities, (entities: Dictionary<SearchProcess>, id: number) => entities[id]);

export const selectInput = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].input
);

export const selectResult = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].result
);

export const selectHits = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].hits
);

export const selectState = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].state
);

export const selectFetching = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].state === SearchProcessState.FETCHING
);

export const selectHasError = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].state === SearchProcessState.ERROR
);

export const selectHasResults = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) =>
    entities[id] && entities[id].state === SearchProcessState.FETCHED && !!entities[id].hits
);

export const selectFilters = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].filters
);

export const selectSelectedFilters = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].filters.selectedFilters
);

export const selectPrimaryFilters = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].filters.primaryFilters
);

export const selectPendingInput = createSelector(
  selectEntities,
  (entities: Dictionary<SearchProcess>, id: number) => entities[id] && entities[id].pendingInput
);
