import 'dart:convert'; // ๐Ÿ‘ˆ [์ถ”๊ฐ€] import 'package:shared_preferences/shared_preferences.dart'; import 'package:uuid/uuid.dart'; // ์•ฑ-๊ณ ์œ  ID์™€ ์‚ฌ์šฉ์ž ์ด๋ฆ„, ๋ ˆ๋ฒจ ์ง„ํ–‰ ์ƒํ™ฉ์„ ๊ด€๋ฆฌํ•˜๋Š” ์„œ๋น„์Šค class IdentityService { static const String _userIdKey = 'app_user_id'; static const String _userNameKey = 'app_user_name'; static const String _maxLevelKey = 'max_unlocked_level'; // ๐Ÿ”ฝ [์ˆ˜์ •] ๋žญํ‚น ์ •๋ณด๋ฅผ Map ํ˜•ํƒœ๋กœ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ Key static const String _lastRankMapKey = 'last_checked_rank_map'; // 1. ์•ฑ-๊ณ ์œ  ID ๊ฐ€์ ธ์˜ค๊ธฐ (์—†์œผ๋ฉด ์ƒ์„ฑ) Future getOrCreateUserId() async { final prefs = await SharedPreferences.getInstance(); String? userId = prefs.getString(_userIdKey); if (userId == null) { userId = const Uuid().v4(); await prefs.setString(_userIdKey, userId); } return userId; } // 2. ๋žญํ‚น์— ๋“ฑ๋กํ•œ ์‚ฌ์šฉ์ž ์ด๋ฆ„ ๊ฐ€์ ธ์˜ค๊ธฐ Future getSavedUserName() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(_userNameKey); } // 3. ๋žญํ‚น ๋“ฑ๋ก ์„ฑ๊ณต ์‹œ, ์‚ฌ์šฉ์ž ์ด๋ฆ„ ์ €์žฅํ•˜๊ธฐ Future saveUserName(String name) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_userNameKey, name); } // 4. ํ˜„์žฌ ์ž ๊ธˆ ํ•ด์ œ๋œ ์ตœ๊ณ  ๋ ˆ๋ฒจ ๊ฐ€์ ธ์˜ค๊ธฐ Future getMaxUnlockedLevel() async { final prefs = await SharedPreferences.getInstance(); return prefs.getInt(_maxLevelKey) ?? 1; } // 5. ์ƒˆ ๋ ˆ๋ฒจ ์ž ๊ธˆ ํ•ด์ œ Future saveMaxUnlockedLevel(int level) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt(_maxLevelKey, level); } // 6. ๐Ÿ”ฝ [์ˆ˜์ •] ๋ชจ๋“  ๋ ˆ๋ฒจ์˜ ๋žญํ‚น ๋งต(Map) ๊ฐ€์ ธ์˜ค๊ธฐ Future> getLastSavedRankMap() async { final prefs = await SharedPreferences.getInstance(); String? jsonString = prefs.getString(_lastRankMapKey); if (jsonString == null) { return {}; // ์ €์žฅ๋œ ๋งต์ด ์—†์œผ๋ฉด ๋นˆ ๋งต ๋ฐ˜ํ™˜ } try { // JSON์€ Map์ด๋ฏ€๋กœ, ํ‚ค๋ฅผ int๋กœ ๋ณ€ํ™˜ final Map decodedMap = jsonDecode(jsonString); return decodedMap.map((key, value) => MapEntry(int.parse(key), value as int)); } catch (e) { // JSON ํŒŒ์‹ฑ ์‹คํŒจ ์‹œ ๋นˆ ๋งต ๋ฐ˜ํ™˜ return {}; } } // 7. ๐Ÿ”ฝ [์ˆ˜์ •] ๋ชจ๋“  ๋ ˆ๋ฒจ์˜ ๋žญํ‚น ๋งต(Map) ์ €์žฅํ•˜๊ธฐ Future saveLastRankMap(Map rankMap) async { final prefs = await SharedPreferences.getInstance(); // JSON ์ €์žฅ์„ ์œ„ํ•ด ํ‚ค๋ฅผ String์œผ๋กœ ๋ณ€ํ™˜ final Map stringKeyMap = rankMap.map((key, value) => MapEntry(key.toString(), value)); String jsonString = jsonEncode(stringKeyMap); await prefs.setString(_lastRankMapKey, jsonString); } }