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

export class Storage {
  private static prefs: preferences.Preferences;

  static async init(context: common.UIAbilityContext) {
    if (!Storage.prefs) {
      try {
        Storage.prefs = await preferences.getPreferences(context, 'app_prefs');
      } catch (error) {

      }
    }
  }

  /**
   * 设置当前登录状态
   * @param value
   */
  static async setLogin(value: boolean) {
    try {
      Storage.prefs.put("is_login", value).catch()
      await Storage.prefs.flush()
    } catch (e) {
    }
  }

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

  static async setToken(value: string) {
    try {
      Storage.prefs.put("token", value).catch()
      await Storage.prefs.flush()
    } catch (e) {
    }
  }

  static getToken(): string {
    try {
      return Storage.prefs.getSync('token', "") as string
    } catch (error) {
      return ""
    }
  }

  static async setUsername(value: string) {
    try {
      Storage.prefs.put("username", value).catch()
      await Storage.prefs.flush()
    } catch (e) {
    }
  }

  static getUsername(): string {
    try {
      return Storage.prefs.getSync('username', "") as string
    } catch (error) {
      return ""
    }
  }
}
