105 lines
2.4 KiB
JavaScript
105 lines
2.4 KiB
JavaScript
const defaultState = {
|
|
loading: false,
|
|
shows: [],
|
|
filter: "",
|
|
perPage: 30,
|
|
selectedImdbId: "",
|
|
show: {
|
|
seasons: [],
|
|
},
|
|
search: "",
|
|
};
|
|
|
|
export default function showStore(state = defaultState, action) {
|
|
switch (action.type) {
|
|
case 'SHOW_LIST_FETCH_PENDING':
|
|
return Object.assign({}, state, {
|
|
loading: true,
|
|
})
|
|
case 'SHOW_LIST_FETCH_FULFILLED':
|
|
let selectedImdbId = "";
|
|
// Select the first show
|
|
if (action.payload.data.length > 0) {
|
|
selectedImdbId = action.payload.data[0].imdb_id;
|
|
}
|
|
return Object.assign({}, state, {
|
|
shows: action.payload.data,
|
|
selectedImdbId: selectedImdbId,
|
|
loading: false,
|
|
})
|
|
case 'SHOW_FETCH_DETAILS_PENDING':
|
|
return Object.assign({}, state, {
|
|
loading: true,
|
|
})
|
|
case 'SHOW_FETCH_DETAILS_FULFILLED':
|
|
return Object.assign({}, state, {
|
|
show: sortEpisodes(action.payload.data),
|
|
loading: false,
|
|
})
|
|
case 'SEARCH_SHOWS_PENDING':
|
|
return Object.assign({}, state, {
|
|
loading: true,
|
|
})
|
|
case 'SEARCH_SHOWS_FULFILLED':
|
|
return Object.assign({}, state, {
|
|
shows: action.payload.data,
|
|
loading: false,
|
|
})
|
|
case 'SELECT_SHOW':
|
|
// Don't select the show if we're fetching another show's details
|
|
if (state.fetchingDetails) {
|
|
return state
|
|
}
|
|
|
|
return Object.assign({}, state, {
|
|
selectedImdbId: action.imdbId,
|
|
})
|
|
default:
|
|
return state
|
|
}
|
|
}
|
|
|
|
function sortEpisodes(show) {
|
|
let episodes = show.episodes;
|
|
delete show["episodes"];
|
|
|
|
if (episodes.length == 0) {
|
|
return show;
|
|
}
|
|
|
|
// Extract the seasons
|
|
let seasons = {};
|
|
for (let ep of episodes) {
|
|
if (!seasons[ep.season]) {
|
|
seasons[ep.season] = { episodes: [] };
|
|
}
|
|
seasons[ep.season].episodes.push(ep);
|
|
}
|
|
|
|
if (seasons.length === 0) {
|
|
return show;
|
|
}
|
|
|
|
// Put all the season in an array
|
|
let sortedSeasons = [];
|
|
for (let season of Object.keys(seasons)) {
|
|
let seasonEpisodes = seasons[season].episodes;
|
|
// Order the episodes in each season
|
|
seasonEpisodes.sort((a,b) => (a.episode - b.episode))
|
|
// Add the season in the list
|
|
sortedSeasons.push({
|
|
season: season,
|
|
episodes: seasonEpisodes,
|
|
})
|
|
}
|
|
|
|
// Order the seasons
|
|
for (let i=0; i<sortedSeasons.length; i++) {
|
|
sortedSeasons.sort((a,b) => (a.season - b.season))
|
|
}
|
|
|
|
show.seasons = sortedSeasons;
|
|
|
|
return show;
|
|
}
|