import { Selector, createSelector } from '@ngrx/store';
import {
  InfoResponse,
  Info,
  EventJson
} from '@ucap-webmessenger/protocol-event';
import { EntityState, createEntityAdapter } from '@ngrx/entity';

export interface InfoListState extends EntityState<Info<EventJson>> {}

export interface State {
  infoListProcessing: boolean;
  infoList: InfoListState;
  infoStatus: InfoResponse | null;
  remainInfo: boolean;
}

export const adapterInfoList = createEntityAdapter<Info<EventJson>>({
  selectId: info => info.seq,
  sortComparer: (a, b) => {
    return a.seq - b.seq;
  }
});

const infoListInitialState: InfoListState = adapterInfoList.getInitialState({});

export const initialState: State = {
  infoListProcessing: false,
  infoList: infoListInitialState,
  infoStatus: null,
  remainInfo: false
};

const {
  selectAll: ngeSelectAllInfoList,
  selectEntities: ngeSelectEntitiesInfoList,
  selectIds: ngeSelectIdsInfoList,
  selectTotal: ngeSelectTotalInfoList
} = adapterInfoList.getSelectors();

export function selectors<S>(selector: Selector<any, State>) {
  const selectInfoList = createSelector(
    selector,
    (state: State) => state.infoList
  );

  return {
    infoListProcessing: createSelector(
      selector,
      (state: State) => state.infoListProcessing
    ),
    remainInfo: createSelector(
      selector,
      (state: State) => state.remainInfo
    ),
    infoList: createSelector(
      selector,
      (state: State) => state.infoList
    ),
    infoStatus: createSelector(
      selector,
      (state: State) => state.infoStatus
    ),

    selectAllInfoList: createSelector(
      selectInfoList,
      ngeSelectAllInfoList
    ),
    selectEntitiesInfoList: createSelector(
      selectInfoList,
      ngeSelectEntitiesInfoList
    ),
    selectInfoList: (seq: number) =>
      createSelector(
        selectInfoList,
        ngeSelectEntitiesInfoList,
        (_, entities) => (!!entities ? entities[seq] : undefined)
      )
  };
}
