// PreferenceManager.ets
import preferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';

export class Storage {
  // 操作对象
  private static instance: preferences.Preferences;

  /**
   * 初始化轻量级存储工具
   *
   * @param context
   */
  static init(context: common.UIAbilityContext) {
    try {
      Storage.instance = preferences.getPreferencesSync(context, { name: 'app_kv_data' })
    } catch (error) {
      console.log("Storage", "init() failed", error)
    }
  }

  /**
   * 设置当前登录状态
   * @param value
   */
  static setLogin(value: boolean) {
    try {
      Storage.instance.putSync("is_login", value)
      Storage.instance.flushSync()
    } catch (error) {
      console.log("Storage", "setLogin() failed", error)
    }
  }

  /**
   * 当前登录状态
   *
   * @returns
   */
  static isLogin(): boolean {
    try {
      return Storage.instance.getSync('is_login', false) === true
    } catch (error) {
      console.log("Storage", "isLogin() failed", error)
      return false
    }
  }

  /**
   * 将登录的token存储到本地
   *
   * @param value
   */
  static setToken(value: string) {
    try {
      Storage.instance.putSync("token", value)
      Storage.instance.flushSync()
    } catch (error) {
      console.log("Storage", "setToken() failed", error)
    }
  }

  /**
   * 获取存储本地的Token
   *
   * @returns
   */
  static getToken(): string {
    try {
      return Storage.instance.getSync('token', "") as string
    } catch (error) {
      console.log("Storage", "getToken() failed", error)
      return ""
    }
  }

  /**
   * 将用户名存储到本地
   *
   * @param value
   */
  static setUsername(value: string) {
    try {
      Storage.instance.putSync("username", value)
      Storage.instance.flushSync()
    } catch (error) {
      console.log("Storage", "setUsername() failed", error)
    }
  }

  /**
   * 获取用户名
   *
   * @returns
   */
  static getUsername(): string {
    try {
      return Storage.instance.getSync('username', "") as string
    } catch (error) {
      console.log("Storage", "getUsername() failed", error)
      return ""
    }
  }
}
