import { Filter } from '@shared/components/filter';
import { PickupShelfState } from './pickup-shelf.state';
import { isEmpty } from 'lodash';
import { PickupShelfDetailsState } from './pickup-shelf-details.state';
import {
  selectDisplayedCompartmentCode,
  selectDisplayedCompartmentInfo,
  selectDisplayedOrderItemProcessingStatus,
  selectOrder,
} from './pickup-shelf-details.selectors';

export function selectProcessId(state: PickupShelfState) {
  return state.processId;
}

export function selectFetchingQuerySettings(state: PickupShelfState) {
  return state.fetchingQuerySettings ?? false;
}

export function selectQuerySettings(state: PickupShelfState) {
  return state.querySettings;
}

export function selectQueryParams(state: PickupShelfState) {
  return state.queryParams;
}

export function selectDefaultFilter(state: PickupShelfState) {
  const querySettings = selectQuerySettings(state);

  return querySettings ? Filter.create(querySettings) : undefined;
}

export function selectFilter(state: PickupShelfState) {
  const queryParams = selectQueryParams(state);

  const defaultFilter = selectDefaultFilter(state);

  if (!defaultFilter) {
    return undefined;
  }

  const filter = Filter.create(defaultFilter);

  // Wenn queryParams undefined ist, dann wird der Filter nicht gesetzt
  if (queryParams === undefined) {
    return filter;
  }

  // Wenn queryParams ein leeres Objekt ist, dann wird der Filter gesetzt, aber ohne Werte (leerer Filter)
  filter.unselectAllFilterOptions();

  // Wenn queryParams ein Objekt mit Werten ist, dann wird der Filter gesetzt
  filter.fromQueryParams(queryParams);

  return filter;
}

export function selectFetchingList(state: PickupShelfState) {
  return state.fetchingList ?? false;
}

export function selectList(state: PickupShelfState) {
  return state.list ?? [];
}

export function selectListHits(state: PickupShelfState) {
  return state.listHits ?? 0;
}

export function selectSelectedListItems(state: PickupShelfState) {
  return state.selectedListItems ?? [];
}

export const selectItemsForPreview = (detailsState: PickupShelfDetailsState) => (state: PickupShelfState) => {
  const orderId = selectOrder(detailsState)?.id;

  let items = state.list.filter((item) => item.orderId === orderId);

  const processingStatus = selectDisplayedOrderItemProcessingStatus(detailsState);
  if (processingStatus) {
    items = items?.filter((oi) => oi.processingStatus === processingStatus);
  }

  const compartmentCode = selectDisplayedCompartmentCode(detailsState);
  if (compartmentCode) {
    items = items?.filter((oi) => oi.compartmentCode === compartmentCode);

    const compartmentInfo = selectDisplayedCompartmentInfo(detailsState);

    if (compartmentInfo) {
      items = items?.filter((oi) => oi.compartmentInfo === compartmentInfo);
    }
  }

  return items;
};
