import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../models/scan_record.dart'; class StorageService { static const _keyIp = 'server_ip'; static const _keyPort = 'server_port'; static const _keyPin = 'server_pin'; static const _keyServerName = 'server_name'; static const _keySuffix = 'server_suffix'; static const _keyContinuous = 'continuous_mode'; static const _keyVibrate = 'vibrate_enabled'; static const _keySound = 'sound_enabled'; static const _keyHistory = 'scan_history'; static Future> loadSettings() async { final prefs = await SharedPreferences.getInstance(); return { 'ip': prefs.getString(_keyIp) ?? '', 'port': prefs.getInt(_keyPort) ?? 8765, 'pin': prefs.getString(_keyPin) ?? '', 'serverName': prefs.getString(_keyServerName) ?? '', 'suffix': prefs.getString(_keySuffix) ?? 'enter', 'continuous': prefs.getBool(_keyContinuous) ?? false, 'vibrate': prefs.getBool(_keyVibrate) ?? true, 'sound': prefs.getBool(_keySound) ?? true, }; } static Future saveServerConnection({ required String ip, required int port, required String pin, String? serverName, }) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_keyIp, ip); await prefs.setInt(_keyPort, port); await prefs.setString(_keyPin, pin); if (serverName != null) { await prefs.setString(_keyServerName, serverName); } } static Future saveSuffix(String suffix) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_keySuffix, suffix); } static Future saveContinuousMode(bool enabled) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_keyContinuous, enabled); } static Future saveFeedbackToggles({required bool vibrate, required bool sound}) async { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_keyVibrate, vibrate); await prefs.setBool(_keySound, sound); } static Future> loadHistory() async { final prefs = await SharedPreferences.getInstance(); final raw = prefs.getStringList(_keyHistory) ?? []; return raw.map((item) { try { return ScanRecord.fromJson(jsonDecode(item) as Map); } catch (_) { return null; } }).whereType().toList(); } static Future addHistoryItem(ScanRecord record) async { final prefs = await SharedPreferences.getInstance(); final history = await loadHistory(); history.insert(0, record); if (history.length > 200) { history.removeRange(200, history.length); } final raw = history.map((e) => jsonEncode(e.toJson())).toList(); await prefs.setStringList(_keyHistory, raw); } static Future clearHistory() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_keyHistory); } }