import 'dart:convert'; import 'dart:math'; import 'package:shared_preferences/shared_preferences.dart'; class OfflineQueue { static const _key = 'delivery_offline_events'; Future enqueue(Map event) async { final prefs = await SharedPreferences.getInstance(); final items = prefs.getStringList(_key) ?? []; final eventId = '${event['event_id'] ?? uuidV4()}'; final alreadyQueued = items.any((item) { final decoded = jsonDecode(item); return decoded is Map && '${decoded['event_id']}' == eventId; }); if (alreadyQueued) return; items.add( jsonEncode({ ...event, 'event_id': eventId, }), ); await prefs.setStringList(_key, items); } static String uuidV4() { final bytes = List.generate(16, (_) => Random.secure().nextInt(256)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; final hex = bytes.map((value) => value.toRadixString(16).padLeft(2, '0')).join(); return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; } Future>> pending() async { final prefs = await SharedPreferences.getInstance(); return (prefs.getStringList(_key) ?? []) .map((item) => jsonDecode(item) as Map) .toList(); } Future removeFirst() async { final prefs = await SharedPreferences.getInstance(); final items = prefs.getStringList(_key) ?? []; if (items.isEmpty) return; await prefs.setStringList(_key, items.sublist(1)); } Future count() async { final prefs = await SharedPreferences.getInstance(); return (prefs.getStringList(_key) ?? []).length; } Future clear() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_key); } }