/**
 * Konichiwa~
 *
 * This module is responsible for Recently Watched. Recently
 * watched is basically a collection of all the anime's that
 * you have watched in the recent past sorted by watch count.
 *
 * IMPORTANT:
 * This module relies on a persistent state. So it must be
 * called in the background script. Don't call this from any
 * content script/popup.
 */ import { IRecentlyWatched } from "./common" ; /**
 * Limiting the maximum amount of recently watched to 20, since
 * beyond that people dont really care. Later on, I might add a
 * way to change this number via the settings page.
 */ let MAX_ITEMS = 10 ; let watchList = [ ] ; ( ( ) => { chrome . storage . local . get ( { recentlyWatched : [ ] } , result => { watchList = result . recentlyWatched ; } ) ; } ) ( ) ; /**
 * Commit the current watchList to the chrome.local storage.
 */ function commit ( ) { chrome . storage . local . set ( { recentlyWatched : watchList } ) ; } export function setMaxItems ( amount ) { MAX_ITEMS = amount ; } export function listCount ( ) { return watchList . length ; } export function clearList ( ) { watchList = [ ] ; commit ( ) ; } param items export function getList ( items = 10 ) { let sorted = Array . from ( watchList ) ; sorted . sort ( ( a , b ) => { return new Date ( b . timestamp ) . valueOf ( ) - new Date ( a . timestamp ) . valueOf ( ) ; } ) ; return sorted . slice ( 0 , items ) ; } param params export function addToList ( params ) { if ( ! params . animeId || ! params . animeName || ! params . url ) { throw new Error ( "[Recently Watched] [Error] animeId, animeName and url must be present." ) ; } for ( let item of watchList ) { if ( item . animeId === params . animeId ) { item . epId = params . epId ; item . epNum = params . epNum ; item . timestamp = params . timestamp || new Date ( ) . toISOString ( ) ; commit ( ) ; return ; } } if ( watchList . length >= MAX_ITEMS ) { watchList . shift ( ) ; } watchList . push ( { animeId : params . animeId , animeName : params . animeName , epId : params . epId , epNum : params . epNum , timestamp : params . timestamp || new Date ( ) . toISOString ( ) , url : params . url , } ) ; commit ( ) ; } param animeId returns export function removeFromList ( animeId ) { for ( let i = 0 ; i < watchList . length ; i ++ ) { if ( watchList [ i ] . animeId === animeId ) { watchList . splice ( i , 1 ) ; commit ( ) ; return true ; } } return false ; }