import { Injectable } from '@angular/core';

@Injectable()
export class CacheService {
	
	constructor() { }

	// Vars
	private _cache: Map<string, any> = new Map<string, any>()
	private maxEntries: number = 100
	


	/**
	 * Returns entry for `key` if it exists in cache.
	 * Updates position of entry according to LRU strategy
	 * 
	 * @tutorial
	```
	let cacheValue = this._cacheService.get(key)
	```
	 * @param key 
	 * @returns undefined | string
	 */
	public get(key: string): any {
		const hasKey = this._cache.has(key)
		let entry: any

		if (hasKey) {
			// peek the entry, re-insert for LRU strategy
			entry = this._cache.get(key)
			this._cache.delete(key)
			this._cache.set(key, entry)
		}
	
		return entry
	}
	

	/**
	 * Checks cache for `key`
	 * 
	 * @param key 
	 * @returns boolean
	 */
	public has(key: string): boolean {
		return this._cache.has(key)
	}


	/**
	 * Will set a cache entry with the given `key` and `value`.
	 * 
	 * @param key 
	 * @param value 
	 * 
	 * @returns void
	 */
	public set(key: string, value: any) {
	
		if (this._cache.size >= this.maxEntries) {
		// least-recently used cache eviction strategy
		const keyToDelete = this._cache.keys().next().value
	
		this._cache.delete(keyToDelete)
		}
	
		this._cache.set(key, value)
	}


}