import dataPreferences from '@ohos.data.preferences'
import { Context } from '@ohos.abilityAccessCtrl'
import { ValueType } from '@ohos.data.ValuesBucket'

const EZVIZ_DEMO_USER_INFO = 'EZVIZ_DEMO_USER_INFO'

export class PreferenceUtil {
  static saveString(context: Context, key: string, value: ValueType) {
    try {
      let preferences: dataPreferences.Preferences | null = null
      let options: dataPreferences.Options = { name: EZVIZ_DEMO_USER_INFO }
      preferences = dataPreferences.getPreferencesSync(context, options)

      try {
        preferences.putSync(key, value)
        preferences.flush()
      } catch (err) {
      }
    } catch (err) {
    }
  }

  static getString(context: Context, key: string): ValueType {
    let result: ValueType = null
    try {
      let preferences: dataPreferences.Preferences | null = null
      let options: dataPreferences.Options = { name: EZVIZ_DEMO_USER_INFO }
      preferences = dataPreferences.getPreferencesSync(context, options)

      try {
        result = preferences.getSync(key, null) as ValueType
      } catch (err) {
      } finally {
        return result
      }
    } catch (err) {
      console.log(`${err}`)
    } finally {
      return result
    }
  }

  static clear(context: Context) {
    let result: ValueType = null
    try {
      let preferences: dataPreferences.Preferences | null = null
      let options: dataPreferences.Options = { name: EZVIZ_DEMO_USER_INFO }
      preferences = dataPreferences.getPreferencesSync(context, options)

      try {
        preferences.clearSync()
        preferences.flush()
      } catch (err) {
      } finally {
        return result
      }
    } catch (err) {
      console.log(`${err}`)
    } finally {
      return result
    }
  }
}