import { produce } from "immer"; const defaultState = { loading: false, movies: new Map(), selectedImdbId: "", lastFetchUrl: "", exploreOptions: {}, }; const formatTorrents = (movie) => { if (!movie.torrents || movie.torrents.length == 0) { return undefined; } let torrentMap = new Map(); movie.torrents.forEach((torrent) => { if (!torrentMap.has(torrent.source)) { torrentMap.set(torrent.source, new Map()); } torrent.metadata = { type: "movie", imdb_id: movie.imdb_id, // eslint-disable-line camelcase quality: torrent.quality, }; torrentMap.get(torrent.source).set(torrent.quality, torrent); }); return torrentMap; }; const formatMovie = (movie) => { movie.fetchingDetails = false; movie.fetchingSubtitles = false; movie.torrents = formatTorrents(movie); return movie; }; const formatMovies = (movies = []) => { let allMoviesInPolochon = true; movies.map((movie) => { formatMovie(movie); if (movie.polochon_url === "") { allMoviesInPolochon = false; } }); movies.sort((a, b) => { if (!allMoviesInPolochon) { return b.year - a.year; } const dateA = new Date(a.date_added); const dateB = new Date(b.date_added); return dateA > dateB ? -1 : dateA < dateB ? 1 : 0; }); let m = new Map(); movies.forEach((movie) => { m.set(movie.imdb_id, movie); }); return m; }; export default (state = defaultState, action) => produce(state, (draft) => { switch (action.type) { case "MOVIE_LIST_FETCH_PENDING": draft.loading = true; break; case "MOVIE_LIST_FETCH_ERROR": draft.loading = false; break; case "MOVIE_LIST_FETCH_FULFILLED": draft.loading = false; draft.movies = formatMovies(action.payload.response.data); if (draft.movies.size > 0) { draft.selectedImdbId = draft.movies.keys().next().value; } break; case "MOVIE_GET_DETAILS_PENDING": draft.movies.get(action.payload.main.imdbId).fetchingDetails = true; break; case "MOVIE_GET_DETAILS_FULFILLED": draft.movies.set( action.payload.response.data.imdb_id, formatMovie(action.payload.response.data) ); break; case "MOVIE_UPDATE_STORE_WISHLIST": draft.movies.get(action.payload.imdbId).wishlisted = action.payload.wishlisted; break; case "MOVIE_GET_EXPLORE_OPTIONS_FULFILLED": draft.exploreOptions = action.payload.response.data; break; case "UPDATE_LAST_MOVIE_FETCH_URL": draft.lastFetchUrl = action.payload.url; break; case "MOVIE_SUBTITLES_UPDATE_PENDING": draft.movies.get(action.payload.main.imdbId).fetchingSubtitles = true; break; case "MOVIE_SUBTITLES_UPDATE_FULFILLED": draft.movies.get(action.payload.main.imdbId).fetchingSubtitles = false; draft.movies.get(action.payload.main.imdbId).subtitles = action.payload.response.data; break; case "SELECT_MOVIE": draft.selectedImdbId = action.payload.imdbId; break; default: return draft; } });