import sortBy from 'lodash-es/sortBy';
import values from 'lodash-es/values';
import filter from 'lodash-es/filter';

import { RootState } from 'mweb/common/reducers/root';
import {
  ALL_CHANNELS,
  ChannelDetails,
  CHANNEL_DIRECTORY_CACHE_TTL,
} from 'mweb/common/reducers/data/channels';

export function getChannelDetails(
  state: RootState,
  channel: string | undefined,
): ChannelDetails | undefined {
  return channel ? state.data.channels.channelDetails[channel] : undefined;
}

export function getChannelsByGame(
  state: RootState,
  game: string,
  pageSize: number = 40,
): ChannelDetails[] {
  if (game === ALL_CHANNELS) {
    const count = state.data.channels.channelsByGameLoadStatus[ALL_CHANNELS]
      ? state.data.channels.channelsByGameLoadStatus[ALL_CHANNELS].pagesLoaded
      : 0;
    return sortBy(
      values(state.data.channels.channelDetails),
      details => -details.viewerCount,
    ).slice(0, pageSize * count);
  }

  return sortBy(
    filter(values(state.data.channels.channelDetails), { game }),
    details => -details.viewerCount,
  );
}

export function doesChannelDataNeedsReinitForGame(
  state: RootState,
  gameName: string,
): boolean {
  return (
    !state.data.channels.channelsByGameLoadStatus[gameName] ||
    getChannelsByGame(state, gameName).length === 0 ||
    state.data.channels.channelsByGameLoadStatus[gameName].lastInitTime <
      new Date().valueOf() - CHANNEL_DIRECTORY_CACHE_TTL
  );
}

export function areAllChannelsLoadedForGame(
  state: RootState,
  gameName: string,
): boolean {
  return !state.data.channels.channelsByGameLoadStatus[gameName]
    .lastChannelCursor;
}
