import jwtDecode from 'jwt-decode';
import { debugTmp } from '../../utils';

export default class LocalStorageEngine {
  constructor(storageKey) {
    this.storageKey = storageKey;
  }

  setToken(token) {
    if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
      return undefined;
    }

    return localStorage.setItem(this.storageKey, token);
  }

  getToken() {
    if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
      return undefined;
    }

    const data = localStorage.getItem(this.storageKey);
    let value;
    let exp;
    try {
      ({ value, exp } = JSON.parse(data));
      // exp undefined 代表该结构不是有效的，所以应该直接返回 data
      if (exp === undefined || value === undefined) {
        // 从 value 中读取 exp
        return data;
      }
    } catch {
      value = data;
    }

    try {
      const decodeValue = jwtDecode(value);
      exp = decodeValue.exp;
    } catch {
      return undefined;
    }

    if (new Date().getTime() > exp * 1000) {
      return undefined;
    }
    return value;
  }

  removeToken() {
    debugTmp('[LocalStorageEngine] removeToken');
    if (typeof window === 'undefined' || typeof window.localStorage === 'undefined') {
      return undefined;
    }

    return localStorage.removeItem(this.storageKey);
  }
}
