interface Cache {
  set(key: string, value: string): void;
  get(key: string): string | null;
  setJSON<T>(key: string, jsonValue: T): void;
  getJSON<T>(key: string): T | null;
  remove(key: string): void;
}

const sessionCache: Cache = {
  set(key, value) {
    if (typeof sessionStorage === 'undefined') return;
    if (key && value) {
      sessionStorage.setItem(key, value);
    }
  },
  get(key) {
    if (typeof sessionStorage === 'undefined') return null;
    if (!key) return null;
    return sessionStorage.getItem(key);
  },
  setJSON<T>(key: any, jsonValue: T) {
    if (jsonValue != null) {
      this.set(key, JSON.stringify(jsonValue));
    }
  },
  getJSON<T>(key: any): T | null {
    const value = this.get(key);
    return value ? JSON.parse(value) : null;
  },
  remove(key) {
    sessionStorage.removeItem(key);
  }
};

const localCache: Cache = {
  set(key, value) {
    if (typeof localStorage === 'undefined') return;
    if (key && value) {
      localStorage.setItem(key, value);
    }
  },
  get(key) {
    if (typeof localStorage === 'undefined') return null;
    if (!key) return null;
    return localStorage.getItem(key);
  },
  setJSON<T>(key: any, jsonValue: T) {
    if (jsonValue != null) {
      this.set(key, JSON.stringify(jsonValue));
    }
  },
  getJSON<T>(key: any): T | null {
    const value = this.get(key);
    return value ? JSON.parse(value) : null;
  },
  remove(key) {
    localStorage.removeItem(key);
  }
};

export default {
  /**
   * 会话级缓存
   */
  session: sessionCache,
  /**
   * 本地缓存
   */
  local: localCache
};
