import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/log/let_log.dart';

class SharedPreferencesUtil {
  static Future<Map<String, dynamic>> getNetCacheResult(String key) async {
    if (!EmptyUtil.isEmpty(key)) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String cacheResult = prefs.getString(key);
      // TODO need解密？
      if (!EmptyUtil.isEmpty(cacheResult)) {
        Map<String, dynamic> map = json.decode(cacheResult);
        if (!EmptyUtil.isEmpty(map)) {
          return map;
        }
      }
    }
    return null;
  }

  static Future<void> setNetCacheResult(String key, String value) async {
    if (!EmptyUtil.isEmpty(key) && !EmptyUtil.isEmpty(value)) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      // TODO need加密？
      prefs.setString(key, value);
    }
    return;
  }

  static Future<bool> setStringValue(String key, String value) async {
    // if (!EmptyUtil.isEmpty(key) && !EmptyUtil.isEmpty(value)) {
    Logger.log('key = ${key}, value = $value');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (null != prefs) {
      return prefs.setString(key, value);
    }
    // }
    return false;
  }

  static Future<String> getStringValue(String key, {String defaultVal = ''}) async {
    if (!EmptyUtil.isEmpty(key)) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      if (null != prefs && prefs.containsKey(key)) {
        return prefs.getString(key);
      }
    }
    return defaultVal;
  }
}
