import { Injectable , EventEmitter } from '@angular/core' ; import { SongResult } from '../../../electron/shared/interfaces/search.interface' ; import { SearchService } from './search.service' ; interface SelectionEvent { songID : number ; selected : boolean ; } @ Injectable ( { providedIn : 'root' } ) export class SelectionService { private searchResults : SongResult [ ] = [ ] ; private selectAllChangedEmitter = new EventEmitter < boolean > ( ) ; private selectionChangedCallbacks : { [ songID ] : ( selection : boolean ) => void ; } = { } ; private allSelected = false ; private selections : { [ songID ] : boolean | undefined ; } = { } ; constructor ( searchService ) { searchService . onSearchChanged ( ( results ) => { this . searchResults = results ; if ( this . allSelected ) { this . selectAll ( ) ; } } ) ; searchService . onNewSearch ( ( results ) => { this . searchResults = results ; this . selectionChangedCallbacks = { } ; this . selections = { } ; this . selectAllChangedEmitter . emit ( false ) ; } ) ; } getSelectedResults ( ) { return this . searchResults . filter ( result => this . selections [ result . id ] == true ) ; } onSelectAllChanged ( callback ) { this . selectAllChangedEmitter . subscribe ( callback ) ; } /**
     * Emits an event when the selection for `songID` needs to change.
     * (note: only one emitter can be registered per `songID`)
     */ onSelectionChanged ( songID , callback ) { this . selectionChangedCallbacks [ songID ] = callback ; } deselectAll ( ) { if ( this . allSelected ) { this . allSelected = false ; this . selectAllChangedEmitter . emit ( false ) ; } setTimeout ( ( ) => this . searchResults . forEach ( result => this . deselectSong ( result . id ) ) , 0 ) ; } selectAll ( ) { if ( ! this . allSelected ) { this . allSelected = true ; this . selectAllChangedEmitter . emit ( true ) ; } setTimeout ( ( ) => this . searchResults . forEach ( result => this . selectSong ( result . id ) ) , 0 ) ; } deselectSong ( songID ) { if ( this . selections [ songID ] ) { this . selections [ songID ] = false ; this . selectionChangedCallbacks [ songID ] ( false ) ; } } selectSong ( songID ) { if ( ! this . selections [ songID ] ) { this . selections [ songID ] = true ; this . selectionChangedCallbacks [ songID ] ( true ) ; } } }