import { Selector, createSelector } from '@ngrx/store';
import { StatusBulkInfo, StatusInfo } from '@ucap-webmessenger/protocol-status';
import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { StatusCode } from '@ucap-webmessenger/core';

export interface StatusBulkInfoState extends EntityState<StatusBulkInfo> {}

export interface State {
  statusBulkInfo: StatusBulkInfoState;
  myStatus: StatusInfo;
  myIdleCheckTime: number;
}

export const adapterStatusBulkInfo = createEntityAdapter<StatusBulkInfo>({
  selectId: statusBulkInfo => statusBulkInfo.userSeq
});

const statusBulkInfoInitialState: StatusBulkInfoState = adapterStatusBulkInfo.getInitialState(
  {}
);

export const initialState: State = {
  statusBulkInfo: statusBulkInfoInitialState,
  myStatus: {
    userSeq: -1,
    pcStatus: StatusCode.OnLine,
    phoneStatus: StatusCode.Offline,
    mobileStatus: StatusCode.Offline,
    conferenceStatus: StatusCode.Offline,
    statusMessage: '',
    mobileConferenceStatus: StatusCode.Offline,
    imessengerStatus: StatusCode.Offline
  },
  myIdleCheckTime: 10
};

const {
  selectAll: ngeSelectAllStatusBulkInfo,
  selectEntities: ngeSelectEntitiesStatusBulkInfo,
  selectIds: ngeSelectIdsStatusBulkInfo,
  selectTotal: ngeSelectTotalStatusBulkInfo
} = adapterStatusBulkInfo.getSelectors();

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

  return {
    selectAllStatusBulkInfo: createSelector(
      selectStatusBulkInfo,
      ngeSelectAllStatusBulkInfo
    ),
    selectEntitiesStatusBulkInfo: createSelector(
      selectStatusBulkInfo,
      ngeSelectEntitiesStatusBulkInfo
    ),
    selectStatusBulkInfo: (userSeq: number) =>
      createSelector(
        selectStatusBulkInfo,
        ngeSelectEntitiesStatusBulkInfo,
        (_, entities) => (!!entities ? entities[userSeq] : undefined)
      ),
    selectMyStatus: createSelector(selector, (state: State) => state.myStatus),
    selectMyIdleCheckTime: createSelector(
      selector,
      (state: State) => state.myIdleCheckTime
    )
  };
}
