import { preferences } from '@kit.ArkData';
import { Context } from '@kit.AbilityKit';
import { StrUtil } from '@pura/harmony-utils';
import { JSON } from '@kit.ArkTS';


export class PrefUtils {
  private static dataPreferences?: preferences.Preferences;
  private static readonly PREF_NAME = 'share_data'

  private constructor() {
  }

  /**
   * 初始化preferences，必须最先调用
   * @param context
   */
  static init(context: Context) {
    if (PrefUtils.dataPreferences == null) {
      try {
        let isGskvSupported = preferences.isStorageTypeSupported(preferences.StorageType.GSKV);
        if (isGskvSupported) {
          let options: preferences.Options = { name: PrefUtils.PREF_NAME, storageType: preferences.StorageType.GSKV };
          PrefUtils.dataPreferences = preferences.getPreferencesSync(context, options);
        } else {
          let options: preferences.Options = { name: PrefUtils.PREF_NAME, storageType: preferences.StorageType.XML };
          PrefUtils.dataPreferences = preferences.getPreferencesSync(context, options);
        }
      } catch (e) {
        let options: preferences.Options = { name: PrefUtils.PREF_NAME };
        PrefUtils.dataPreferences = preferences.getPreferencesSync(context, options);
      }
    }
  }

  static put(name: string, value: preferences.ValueType) {
    if (value !== undefined) {
      PrefUtils.dataPreferences?.putSync(name, value)
      PrefUtils.dataPreferences?.flushSync()
    }
  }

  static getString(name: string): string {
    return PrefUtils.dataPreferences?.getSync(name, "") as string;
  }

  static getBoolean(name: string, defaultValue: boolean = false): boolean {
    return PrefUtils.dataPreferences?.getSync(name, defaultValue) as boolean;
  }

  static getNumber(name: string): number {
    return PrefUtils.dataPreferences?.getSync(name, 0) as number;
  }

  static getStringArray(name: string): Array<string> {
    let str = PrefUtils.dataPreferences?.getSync(name, '') as string
    if (StrUtil.isNotEmpty(str)) {
      return JSON.parse(str) as Array<string>
    }
    return new Array<string>()
  }

  static remove(name: string) {
    PrefUtils.dataPreferences?.deleteSync(name);
    PrefUtils.dataPreferences?.flushSync()
  }
}

