|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:flutter/foundation.dart'; |
| 4 | +import '../services/responder_state_service.dart'; |
| 5 | +import '../services/location_service.dart'; |
| 6 | +import '../services/tile_prefetch_service.dart'; |
| 7 | + |
| 8 | +/// Acts as the glue: listens to [ResponderStateService]. When active, it uses |
| 9 | +/// [LocationService] to get the location, and then triggers an offline tile |
| 10 | +/// prefetch centered around the responder for 5km using [TilePrefetchService]. |
| 11 | +class ResponderController { |
| 12 | + final ResponderStateService _stateService; |
| 13 | + final LocationService _locationService; |
| 14 | + final TilePrefetchService _prefetchService; |
| 15 | + |
| 16 | + StreamSubscription<ResponderState>? _stateSub; |
| 17 | + bool _hasTriggeredForCurrentSession = false; |
| 18 | + |
| 19 | + ResponderController({ |
| 20 | + required ResponderStateService stateService, |
| 21 | + required LocationService locationService, |
| 22 | + required TilePrefetchService prefetchService, |
| 23 | + }) : _stateService = stateService, |
| 24 | + _locationService = locationService, |
| 25 | + _prefetchService = prefetchService { |
| 26 | + _init(); |
| 27 | + } |
| 28 | + |
| 29 | + void _init() { |
| 30 | + _stateSub = _stateService.stateStream.listen(_onStateChanged); |
| 31 | + |
| 32 | + // Check initial state |
| 33 | + _onStateChanged(_stateService.currentState); |
| 34 | + } |
| 35 | + |
| 36 | + Future<void> _onStateChanged(ResponderState state) async { |
| 37 | + if (state == ResponderState.inactive) { |
| 38 | + _hasTriggeredForCurrentSession = false; |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + if (state == ResponderState.active) { |
| 43 | + if (_hasTriggeredForCurrentSession) return; |
| 44 | + _hasTriggeredForCurrentSession = true; |
| 45 | + |
| 46 | + // 1. Get the current location |
| 47 | + final location = await _locationService.getCurrentLocation(); |
| 48 | + |
| 49 | + if (location == null) { |
| 50 | + debugPrint('ResponderController: Failed to get location, skipping tile prefetch'); |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + // 2. Trigger tile prefetch for 5km radius |
| 55 | + debugPrint('Starting tile prefetch for radius'); |
| 56 | + |
| 57 | + try { |
| 58 | + await _prefetchService.startPrefetchForRadius( |
| 59 | + location, |
| 60 | + 5000, // 5km radius |
| 61 | + ); |
| 62 | + } catch (e) { |
| 63 | + debugPrint('ResponderController: Failed to start prefetch: $e'); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + void dispose() { |
| 69 | + _stateSub?.cancel(); |
| 70 | + } |
| 71 | +} |
0 commit comments