import { RootState } from 'mweb/common/reducers/root';
import { GameDetails } from 'mweb/common/reducers/data/games';
import {
  ChannelDetails,
  ALL_CHANNELS,
} from 'mweb/common/reducers/data/channels';
import {
  getGameDetailsForGameAlias,
  getGameNameForGameAlias,
} from 'mweb/common/selectors/data/games';
import { getChannelsByGame } from 'mweb/common/selectors/data/channels';

export function getCurrentGameForChannelDirectory(
  state: RootState,
): GameDetails | undefined {
  const gameAlias = state.pages.channelDirectory.currentGameAlias;
  return gameAlias ? getGameDetailsForGameAlias(state, gameAlias) : undefined;
}

export function channelDirectoryIsLoaded(state: RootState): boolean {
  const gameAlias = state.pages.channelDirectory.currentGameAlias;
  if (!gameAlias) {
    return false;
  }

  if (gameAlias === ALL_CHANNELS) {
    /**
     * we have some channels or we have a record of a previous load attempt
     */
    return (
      getChannelsByGame(state, ALL_CHANNELS).length > 0 ||
      !!state.data.channels.channelsByGameLoadStatus[ALL_CHANNELS]
    );
  }

  const gameName = getGameNameForGameAlias(state, gameAlias);
  if (!gameName) {
    /**
     * we don't have any data about this game and
     * we have a record of a previous load attempt
     */
    return !!state.data.channels.channelsByGameLoadStatus[gameAlias];
  }

  return (
    /**
     * we have data about this game and either:
     * - we have some channels for it
     * - we have a record of a previous load attempt
     */
    getChannelsByGame(state, gameName).length > 0 ||
    !!state.data.channels.channelsByGameLoadStatus[gameName]
  );
}

export function channelDirectoryChannelList(
  state: RootState,
  pageSize: number = 40,
): ChannelDetails[] {
  const gameAlias = state.pages.channelDirectory.currentGameAlias;
  if (!gameAlias) {
    return [];
  }

  const gameName =
    gameAlias === ALL_CHANNELS
      ? ALL_CHANNELS
      : getGameNameForGameAlias(state, gameAlias);
  if (!gameName) {
    return [];
  }

  return getChannelsByGame(state, gameName, pageSize);
}
