import { Inject, Injectable, InjectionToken } from '@angular/core';

export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
  providedIn: 'root',
  factory: () => localStorage
});

@Injectable({
  providedIn: 'root'
})
export class BrowserStorageService {
  constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {}

  get(key: string) {
    // @ts-ignore
    return JSON.parse(this.storage.getItem(key)) as T;
  }

  set(key: string, value: any) {
    if (!value && value === undefined) { return; }
    const arr = JSON.stringify(value);
    this.storage.setItem(key, arr);
  }

  remove(key: string) {
    this.storage.removeItem(key);
  }

  clear() {
    this.storage.clear();
  }
}
