import { OrderedMap, Map, fromJS } from "immutable"; const defaultState = Map({ loading: false, shows: OrderedMap(), filter: "", selectedImdbId: "", lastFetchUrl: "", exploreOptions: Map() }); const handlers = { SHOW_LIST_FETCH_PENDING: state => state.set("loading", true), SHOW_LIST_FETCH_FULFILLED: (state, action) => { let shows = Map(); action.payload.response.data.map(function(show) { show.fetchingDetails = false; show.fetchingSubtitles = false; shows = shows.set(show.imdb_id, fromJS(show)); }); let selectedImdbId = ""; if (shows.size > 0) { // Sort by year shows = shows.sort((a, b) => b.get("year") - a.get("year")); selectedImdbId = shows.first().get("imdb_id"); } return state.delete("shows").merge( Map({ shows: shows, filter: "", loading: false, selectedImdbId: selectedImdbId }) ); }, SHOW_GET_DETAILS_PENDING: (state, action) => state.setIn(["shows", action.payload.main.imdbId, "fetchingDetails"], true), SHOW_GET_DETAILS_FULFILLED: (state, action) => { let show = action.payload.response.data; show.fetchingDetails = false; show.fetchingSubtitles = false; return state.setIn(["shows", show.imdb_id], fromJS(show)); }, SHOW_GET_EXPLORE_OPTIONS_FULFILLED: (state, action) => state.set("exploreOptions", fromJS(action.payload.response.data)), SHOW_UPDATE_STORE_WISHLIST: (state, action) => { let season = action.payload.season; let episode = action.payload.episode; if (action.payload.wishlisted) { if (season === null) { season = 0; } if (episode === null) { episode = 0; } } return state.mergeIn( ["shows", action.payload.imdbId], Map({ tracked_season: season, tracked_episode: episode }) ); }, UPDATE_LAST_SHOWS_FETCH_URL: (state, action) => state.set("lastFetchUrl", action.payload.url), SELECT_SHOW: (state, action) => state.set("selectedImdbId", action.payload.imdbId), SHOWS_UPDATE_FILTER: (state, action) => state.set("filter", action.payload.filter) }; export default (state = defaultState, action) => handlers[action.type] ? handlers[action.type](state, action) : state;