summaryrefslogtreecommitdiff
path: root/frontend/src/redux/games.ts
blob: 5e21211aa40e45b3eaf36df7b8247db12bfc8e74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { List, Map } from 'immutable';
import { combineReducers } from 'redux';
import { ApiLobby } from '../api/model';
import { GlobalState } from '../reducers';
import { Action } from './actions/all';
import { ENTER_LOBBY, UPDATE_GAMES } from './actions/lobby';

export type GamesState = {
  all: Map<string, ApiLobby>,
  current: string | null
};

export const createGamesReducer = () => {
  return combineReducers({
    all: allGamesReducer,
    current: currentGameIdReducer
  })
};

export const allGamesReducer = (state: Map<string, ApiLobby> = Map(), action: Action) => {
  switch (action.type) {
    case UPDATE_GAMES:
      const newGames = mapify(action.games);
      return state.merge(newGames);
    default:
      return state;
  }
};

function mapify(games: ApiLobby[]): Map<string, ApiLobby> {
  let newGames: {[id:string]:ApiLobby} = {};
  games.forEach(g => newGames[`${g.id}`] = g);
  return Map(newGames);
}

export const currentGameIdReducer = (state: string | null = null, action: Action) => {
  switch (action.type) {
    case ENTER_LOBBY:
      return `${action.gameId}`;
    default:
      return state;
  }
};

export const getAllGames = (state: GlobalState): List<ApiLobby> => state.games.all.toList();
export const getCurrentGame = (state: GlobalState): ApiLobby | null => {
  if (state.games.current == null) {
    return null;
  }
  return state.games.all.get(state.games.current) || null;
};
bgstack15