const DEBUG_KEY = "SATURN_DEBUG_CONFIG";

class Store {
  localStorage = window.localStorage;

  get<T = Record<string, any>>(key: string): string | T | null {
    const { localStorage } = this;
    if (!localStorage) return null;
    const value = localStorage.getItem(key);
    if (!value) return value as string;
    try {
      return JSON.parse(value);
    } catch (e) {
      return localStorage.getItem(key);
    }
  }
  set(key: string, value: Record<string, any> | string) {
    const { localStorage } = this;
    if (typeof value === "object") {
      localStorage.setItem(key, JSON.stringify(value));
    } else {
      localStorage.setItem(key, value);
    }
  }
  remove(key: string) {
    const { localStorage } = this;
    localStorage.removeItem(key);
  }
  clear() {
    const { localStorage } = this;
    localStorage.clear();
  }
}

const storage = new Store();

class DebugConfig {
  /** 是否开启 */
  enabled: boolean = false;
}

function getDebugConfig() {
  const config = storage.get<DebugConfig>(DEBUG_KEY);
  if (config && typeof config === "object") {
    return config;
  } else {
    return new DebugConfig();
  }
}

const config = getDebugConfig();

/** 是否开启了 debug 模式 */
function isEnabled() {
  return config.enabled;
}

// eslint-disable-next-line import/no-anonymous-default-export
export default {
  DEBUG_KEY,
  /** 是否开启了 debug 模式 */
  enabled: isEnabled(),
  config,
};
