import { produce } from "immer"; const defaultState = { fetching: false, searching: false, torrents: new Map(), count: 0, searchResults: [], }; // Group the torrents by imdb id const formatTorrents = (input) => { let torrents = new Map(); if (!input) { return torrents; } input.forEach((t) => { let key; switch (t.type) { case "movie": key = t.video ? t.video.imdb_id : "unknown"; break; case "episode": key = t.video ? t.video.show_imdb_id : "unknown"; break; default: key = "unknown"; break; } if (!torrents.has(key)) { torrents.set(key, []); } torrents.get(key).push(t); }); return torrents; }; export default (state = defaultState, action) => produce(state, (draft) => { switch (action.type) { case "TORRENTS_FETCH_PENDING": draft.fetching = true; break; case "TORRENTS_FETCH_FULFILLED": draft.fetching = false; draft.torrents = formatTorrents(action.payload.response.data); draft.count = action.payload.response.data ? action.payload.response.data.length : 0; break; case "TORRENTS_SEARCH_PENDING": draft.searching = true; break; case "TORRENTS_SEARCH_FULFILLED": draft.searching = false; draft.searchResults = action.payload.response.data; break; case "TORRENTS_SEARCH_CLEAR": draft.searchResults = []; break; default: return draft; } });