import {Injectable, Inject} from '@angular/core'; import {SearchResult} from './search-result'; import {v4} from 'node-uuid/node'; import {pull, map, forEach, clone, find} from 'lodash'; import {ISerializable} from '../cache/serializeable.interface'; import {ICache, CACHE} from '../cache/cache.interface'; @Injectable() export class SearchResultCollection implements ISerializable { private resultReferences: ResultReference[] = []; private COLLECTION_KEY: string = 'ose-search-result-keys'; constructor(@Inject(CACHE) private cache: ICache) { cache.restore(this.COLLECTION_KEY, this); } get(key: string): SearchResult { return this.cache.get(key, SearchResult); } get results(): ResultReference[] { return this.resultReferences; } addResult( searchResult: SearchResult, name: string = 'New Result'): ResultReference { const key = v4(); const ref = new ResultReference(key, name); this.resultReferences.push(ref); this.cache.set(ref.key, searchResult); this.save(); return ref; } removeResult(key: string): boolean { pull( this.resultReferences, find(this.resultReferences, {key: key}) ); return this.cache.delete(key); } private save(): void { this.cache.set(this.COLLECTION_KEY, this); } clear(): void { forEach( clone(this.results), ref => this.removeResult(ref.key) ); } serialize(): string { return JSON.stringify( map(this.results, res => res.serialize()) ); } deserialize(from: string): SearchResultCollection { try { const parsedJson = JSON.parse(from); this.resultReferences = map( parsedJson, (obj: string) => { return new ResultReference().deserialize(obj); } ); } catch (e) { console.error(`ResultReferenceCollection deserialization error: ${e}`); } return this; } } export class ResultReference implements ISerializable { key: string; name: string; constructor(key: string = '', name: string = '') { this.key = key; this.name = name; } serialize(): string { return JSON.stringify({key: this.key, name: this.name}); } deserialize(from: string): ResultReference { try { const obj = JSON.parse(from); this.key = obj.key; this.name = obj.name; } catch (e) { console.error(`ResultReference deserialization error: ${e}`); } return this; } }