import 'package:comunic/helpers/websocket_helper.dart'; import 'package:comunic/lists/forez_presences_set.dart'; import 'package:comunic/models/forez_presence.dart'; /// Presence helper /// /// @author Pierre Hubert int? _cachedGroup; PresenceSet? _cache; class ForezPresenceHelper { /// Refresh presence cache /// /// Throws in case of failure static Future refreshCache(int groupID) async { final response = await ws("forez_presence/list", {"group": groupID}); final list = response .cast() .map((element) { final cut = element.split(",").map((e) => int.parse(e)).toList(); assert(cut.length == 4); return Presence( userID: cut[0], year: cut[1], month: cut[2], day: cut[3]); }) .toList() .cast(); _cachedGroup = groupID; _cache = PresenceSet()..addAll(list); } /// Initialize cache if required static Future _checkCache(int groupID) async { if (_cache == null || _cachedGroup != groupID) await refreshCache(groupID); } /// Get the presences of a given user /// /// Throws in case of failure static Future getForUser(int groupID, int? userID) async { await _checkCache(groupID); return _cache!.getForUser(userID); } /// Get all the available presences /// /// Throws in case of failure static Future getAll(int groupID) async { await _checkCache(groupID); return _cache; } /// Add a new day of presence /// /// Throws in case of failure static Future addDay(int groupID, DateTime dt) async => await ws("forez_presence/add_day", { "group": groupID, "year": dt.year, "month": dt.month, "day": dt.day, }); /// Remove a new day of presence /// /// Throws in case of failure static Future delDay(int groupID, DateTime dt) async => await ws("forez_presence/del_day", { "group": groupID, "year": dt.year, "month": dt.month, "day": dt.day, }); }