import 'package:shared_preferences/shared_preferences.dart';
import '../errors/exceptions.dart';

class LocalStorage {
  final SharedPreferences _prefs;

  LocalStorage(this._prefs);

  static Future<LocalStorage> init() async {
    final prefs = await SharedPreferences.getInstance();
    return LocalStorage(prefs);
  }

  // String
  Future<bool> setString(String key, String value) async {
    try {
      return await _prefs.setString(key, value);
    } catch (e) {
      throw StorageException('写入本地存储失败: $e');
    }
  }

  String? getString(String key) {
    try {
      return _prefs.getString(key);
    } catch (e) {
      throw StorageException('读取本地存储失败: $e');
    }
  }

  // Int
  Future<bool> setInt(String key, int value) async {
    try {
      return await _prefs.setInt(key, value);
    } catch (e) {
      throw StorageException('写入本地存储失败: $e');
    }
  }

  int? getInt(String key) {
    try {
      return _prefs.getInt(key);
    } catch (e) {
      throw StorageException('读取本地存储失败: $e');
    }
  }

  // Double
  Future<bool> setDouble(String key, double value) async {
    try {
      return await _prefs.setDouble(key, value);
    } catch (e) {
      throw StorageException('写入本地存储失败: $e');
    }
  }

  double? getDouble(String key) {
    try {
      return _prefs.getDouble(key);
    } catch (e) {
      throw StorageException('读取本地存储失败: $e');
    }
  }

  // Bool
  Future<bool> setBool(String key, bool value) async {
    try {
      return await _prefs.setBool(key, value);
    } catch (e) {
      throw StorageException('写入本地存储失败: $e');
    }
  }

  bool? getBool(String key) {
    try {
      return _prefs.getBool(key);
    } catch (e) {
      throw StorageException('读取本地存储失败: $e');
    }
  }

  // StringList
  Future<bool> setStringList(String key, List<String> value) async {
    try {
      return await _prefs.setStringList(key, value);
    } catch (e) {
      throw StorageException('写入本地存储失败: $e');
    }
  }

  List<String>? getStringList(String key) {
    try {
      return _prefs.getStringList(key);
    } catch (e) {
      throw StorageException('读取本地存储失败: $e');
    }
  }

  // Remove & Clear
  Future<bool> remove(String key) async {
    try {
      return await _prefs.remove(key);
    } catch (e) {
      throw StorageException('删除本地存储失败: $e');
    }
  }

  Future<bool> clear() async {
    try {
      return await _prefs.clear();
    } catch (e) {
      throw StorageException('清空本地存储失败: $e');
    }
  }

  bool containsKey(String key) {
    return _prefs.containsKey(key);
  }
}
