import { Inject, Injectable, InjectionToken } from '@angular/core';
import {ADMIN_INFO_OBJECT} from "../services/local-storage.namespace";

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();
  }

  /**
   * 校验当前用户是否拥有按钮权限
   * @param btnCode
   */
  public isBtnCompetence(btnCode: string): boolean {
    let buttonList = [];
    buttonList = this.get(ADMIN_INFO_OBJECT)['buttonList'];
    if (buttonList != null && buttonList.length > 0) {
      if (buttonList.find((b:any) => b.permissionCode === btnCode) != null) {
        return true;
      }
    }
    return false;
  }
}
