| 1 | import 'dart:async'; |
| 2 | |
| 3 | import 'package:built_collection/built_collection.dart'; |
| 4 | import 'package:dio/dio.dart'; |
| 5 | import 'package:flutter/material.dart'; |
| 6 | import 'package:latlong2/latlong.dart'; |
| 7 | import 'package:openapi/openapi.dart'; |
| 8 | import 'package:retry/retry.dart'; |
| 9 | |
| 10 | import 'package:aero/screens/home/service.dart'; |
| 11 | import 'package:aero/services/main.dart'; |
| 12 | import 'package:aero/services/widget_update_service.dart'; |
| 13 | import 'package:aero/utils/error.dart'; |
| 14 | |
| 15 | enum FlightPanelState { |
| 16 | idle, |
| 17 | loadingFlight, |
| 18 | selectingFlight, |
| 19 | showingFlight, |
| 20 | } |
| 21 | |
| 22 | enum SearchState { |
| 23 | idle, |
| 24 | loading, |
| 25 | } |
| 26 | |
| 27 | class HomeController extends ChangeNotifier |
| 28 | HomeController({ |
| 29 | HomeService? homeService, |
| 30 | FlightDataService? flightDataService, |
| 31 | }) : _service = homeService ?? HomeService |
| 32 | _flightService = flightDataService ?? FlightDataService(); |
| 33 | |
| 34 | final HomeService _service; |
| 35 | final FlightDataService _flightService; |
| 36 | |
| 37 | final TextEditingController flightController = |
| 38 | Timer? _debounce; |
| 39 | Timer? _trackPollingTimer; |
| 40 | Timer? _countdownTimer; |
| 41 | int _secondsUntilNextUpdate = 30; |
| 42 | |
| 43 | FlightPanelState panelState = FlightPanelState. |
| 44 | SearchState searchState = SearchState. |
| 45 | |
| 46 | String? error; |
| 47 | AirportEntity? departureAirport; |
| 48 | AirportEntity? arrivalAirport; |
| 49 | DateTime? selectedDate; |
| 50 | BuiltList<FlightEntity> flights = |
| 51 | List<Object> results = [] |
| 52 | AirlineEntity? selectedAirline; |
| 53 | String? selectedFlightNumber; |
| 54 | FlightResponseEntity? flightInfo; |
| 55 | List<LatLng> coordinates = [] |
| 56 | List<LatLng> flightTrackPoints = [] |
| 57 | FlightPositionEntity? currentPosition; |
| 58 | BuiltList<FlightResponseEntity> trackedFlights = |
| 59 | bool loadingTrackedFlights = false; |
| 60 | bool isInAir = false; |
| 61 | CancelToken? _cancelToken; |
| 62 | BuiltList<FlightPositionEntity> flightPositions = |
| 63 | FlightSearchResponseEntity? flightSearchResults; |
| 64 | String? pendingIata; |
| 65 | String? pendingIcao; |
| 66 | DateTime? pendingDate; |
| 67 | |
| 68 | List<AirportEntity> nearbyAirports = [] |
| 69 | CancelToken? _airportsCancelToken; |
| 70 | List<double>? _lastAirportBounds |
| 71 | |
| 72 | int get secondsUntilNextUpdate => _secondsUntilNextUpdate; |
| 73 | bool get isTrackingActive => |
| 74 | _trackPollingTimer != null && _trackPollingTimer!.isActive |
| 75 | |
| 76 | void initialize() { |
| 77 | loadTrackedFlights(); |
| 78 | } |
| 79 | |
| 80 | @override |
| 81 | void dispose() { |
| 82 | _controllerCleanup(); |
| 83 | flightController.dispose(); |
| 84 | super.dispose(); |
| 85 | } |
| 86 | |
| 87 | void _controllerCleanup() { |
| 88 | _debounce?.cancel(); |
| 89 | _trackPollingTimer?.cancel(); |
| 90 | _countdownTimer?.cancel(); |
| 91 | _airportsCancelToken?.cancel('Controller disposed'); |
| 92 | } |
| 93 | |
| 94 | void clearError() { |
| 95 | if (error != null) { |
| 96 | error = null; |
| 97 | notifyListeners(); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | void debounceSearch(String |
| 102 | _debounce?.cancel(); |
| 103 | _debounce = Timer(const |
| 104 | search(query); |
| 105 | }); |
| 106 | } |
| 107 | |
| 108 | Future<void> search |
| 109 | if (query.isEmpty || query.length == |
| 110 | results = []; |
| 111 | notifyListeners(); |
| 112 | return; |
| 113 | } |
| 114 | |
| 115 | if (_cancelToken != null) { |
| 116 | _cancelToken!.cancel("User is searching for new results"); |
| 117 | } |
| 118 | _cancelToken = CancelToken(); |
| 119 | |
| 120 | searchState = SearchState.loading; |
| 121 | results = []; |
| 122 | notifyListeners(); |
| 123 | |
| 124 | try { |
| 125 | results = await _service.search(query |
| 126 | } finally { |
| 127 | searchState = SearchState.idle; |
| 128 | notifyListeners(); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | void clearSearchResults() { |
| 133 | results.clear(); |
| 134 | notifyListeners(); |
| 135 | } |
| 136 | |
| 137 | /// Fetch airports inside the given map bounds and expose them for plotting. |
| 138 | /// Skips redundant requests when the bounds barely changed, and cancels any |
| 139 | /// in-flight request when a newer pan supersedes it. |
| 140 | Future<void> loadAirportsInBounds |
| 141 | double minLat, |
| 142 | double maxLat, |
| 143 | double minLng, |
| 144 | double maxLng, |
| 145 | ) async { |
| 146 | final bounds = [minLat, maxLat, |
| 147 | if (_lastAirportBounds != null) { |
| 148 | var unchanged = true; |
| 149 | for (var i = 0 |
| 150 | if ((bounds[i] - _lastAirportBounds![i]).abs |
| 151 | unchanged = false; |
| 152 | break; |
| 153 | } |
| 154 | } |
| 155 | if (unchanged) return; |
| 156 | } |
| 157 | _lastAirportBounds = bounds; |
| 158 | |
| 159 | _airportsCancelToken?.cancel('Map moved, fetching new airports'); |
| 160 | final token = CancelToken() |
| 161 | _airportsCancelToken = token; |
| 162 | |
| 163 | final airports = await _service. |
| 164 | minLat, |
| 165 | maxLat, |
| 166 | minLng, |
| 167 | maxLng, |
| 168 | cancelToken: token, |
| 169 | ); |
| 170 | |
| 171 | // A newer pan may have superseded this request while it was in flight; |
| 172 | // ignore the (possibly cancelled/empty) result so we don't clear markers. |
| 173 | if (token != _airportsCancelToken || token.isCancelled) return |
| 174 | |
| 175 | nearbyAirports = airports.toList(); |
| 176 | notifyListeners(); |
| 177 | } |
| 178 | |
| 179 | void selectAirport(AirportEntity |
| 180 | if (departureAirport == null) { |
| 181 | departureAirport = airport; |
| 182 | } else { |
| 183 | arrivalAirport = airport; |
| 184 | } |
| 185 | flightController.clear(); |
| 186 | clearSearchResults(); |
| 187 | notifyListeners(); |
| 188 | } |
| 189 | |
| 190 | void selectAirline( |
| 191 | AirlineEntity airline, { |
| 192 | String? currentInput, |
| 193 | }) { |
| 194 | selectedAirline = airline; |
| 195 | error = null; |
| 196 | final text = currentInput?.trim |
| 197 | String? remainingText; |
| 198 | final upperText = text.toUpperCase |
| 199 | final iata = airline.iata; |
| 200 | final icao = airline.icao; |
| 201 | |
| 202 | if (iata.isNotEmpty && upperText.startsWith |
| 203 | remainingText = text.substring(iata.length) |
| 204 | } else if (icao.isNotEmpty && upperText. |
| 205 | remainingText = text.substring(icao.length) |
| 206 | } else if (text.isNotEmpty && |
| 207 | airline.name.isNotEmpty && |
| 208 | upperText.contains(airline.name.toUpperCase |
| 209 | final nameIndex = upperText.indexOf |
| 210 | if (nameIndex != -1) { |
| 211 | remainingText = |
| 212 | text.substring(nameIndex + airline.name |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | if (remainingText != null && |
| 217 | remainingText.isNotEmpty && |
| 218 | RegExp(r'\d').hasMatch |
| 219 | final match = RegExp( |
| 220 | if (match != null) { |
| 221 | selectedFlightNumber = match.group(0) |
| 222 | flightController.clear(); |
| 223 | } |
| 224 | } else { |
| 225 | flightController.clear(); |
| 226 | } |
| 227 | clearSearchResults(); |
| 228 | notifyListeners(); |
| 229 | } |
| 230 | |
| 231 | void selectFlightNumber(String |
| 232 | selectedFlightNumber = flightNumber; |
| 233 | error = null; |
| 234 | flightController.clear(); |
| 235 | notifyListeners(); |
| 236 | } |
| 237 | |
| 238 | void clearAirline() { |
| 239 | selectedAirline = null; |
| 240 | error = null; |
| 241 | notifyListeners(); |
| 242 | } |
| 243 | |
| 244 | void clearFlightNumber() { |
| 245 | selectedFlightNumber = null; |
| 246 | error = null; |
| 247 | notifyListeners(); |
| 248 | } |
| 249 | |
| 250 | void clearAirports() { |
| 251 | arrivalAirport = null; |
| 252 | departureAirport = null; |
| 253 | error = null; |
| 254 | notifyListeners(); |
| 255 | } |
| 256 | |
| 257 | void clearDepartureAirport() { |
| 258 | departureAirport = null; |
| 259 | error = null; |
| 260 | notifyListeners(); |
| 261 | } |
| 262 | |
| 263 | Future<void> loadTrackedFlights |
| 264 | loadingTrackedFlights = true; |
| 265 | notifyListeners(); |
| 266 | try { |
| 267 | trackedFlights = await _flightService.getTrackedFlights() |
| 268 | } catch (error,stack) { |
| 269 | print(error); |
| 270 | print(stack); |
| 271 | } finally { |
| 272 | loadingTrackedFlights = false; |
| 273 | notifyListeners(); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | Future<void> loadFlightsForSelection |
| 278 | selectedDate = date; |
| 279 | flights = BuiltList.from([]) |
| 280 | panelState = FlightPanelState.loadingFlight; |
| 281 | error = null; |
| 282 | notifyListeners(); |
| 283 | try { |
| 284 | if (departureAirport != null && arrivalAirport != |
| 285 | flights = await _flightService.getFlights( |
| 286 | departureAirport!.iataCode ?? departureAirport!.ident, |
| 287 | arrivalAirport!.iataCode ?? arrivalAirport!.ident, |
| 288 | date.toIso8601String(), |
| 289 | ); |
| 290 | panelState = FlightPanelState.idle; |
| 291 | } else if (selectedAirline != null && |
| 292 | await loadFlightInfo( |
| 293 | "${selectedAirline!.iata}$ |
| 294 | "${selectedAirline!.icao}$ |
| 295 | date, |
| 296 | ); |
| 297 | } |
| 298 | } catch (_) { |
| 299 | selectedDate = null; |
| 300 | panelState = FlightPanelState.idle; |
| 301 | } finally { |
| 302 | notifyListeners(); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | Future<void> loadFlightInfo |
| 307 | String iataCode, |
| 308 | String icaoCode, |
| 309 | DateTime date, { |
| 310 | bool forceUpdate = false, |
| 311 | String? faFlightId, |
| 312 | }) async { |
| 313 | error = null; |
| 314 | panelState = FlightPanelState.loadingFlight; |
| 315 | notifyListeners(); |
| 316 | |
| 317 | try { |
| 318 | if (faFlightId != null) { |
| 319 | final info = await _flightService. |
| 320 | iataCode, |
| 321 | icaoCode, |
| 322 | date: date, |
| 323 | forceUpdate: forceUpdate, |
| 324 | faFlightId: faFlightId, |
| 325 | ); |
| 326 | |
| 327 | if (info == null) { |
| 328 | error = 'No flight information found'; |
| 329 | panelState = FlightPanelState.idle; |
| 330 | notifyListeners(); |
| 331 | return; |
| 332 | } |
| 333 | |
| 334 | _processFlightInfo(info, iataCode, icaoCode, |
| 335 | return; |
| 336 | } |
| 337 | |
| 338 | final searchResults = await _flightService. |
| 339 | iataCode, |
| 340 | icaoCode, |
| 341 | date: date, |
| 342 | ); |
| 343 | |
| 344 | if (searchResults == null || searchResults. |
| 345 | error = 'No flights found'; |
| 346 | panelState = FlightPanelState.idle; |
| 347 | notifyListeners(); |
| 348 | return; |
| 349 | } |
| 350 | |
| 351 | if (searchResults.count > 1) { |
| 352 | flightSearchResults = searchResults; |
| 353 | panelState = FlightPanelState.selectingFlight; |
| 354 | pendingIata = iataCode; |
| 355 | pendingIcao = icaoCode; |
| 356 | pendingDate = date; |
| 357 | notifyListeners(); |
| 358 | return; |
| 359 | } |
| 360 | |
| 361 | final singleFlight = searchResults.flights. |
| 362 | final info = await _flightService. |
| 363 | iataCode, |
| 364 | icaoCode, |
| 365 | date: date, |
| 366 | forceUpdate: forceUpdate, |
| 367 | faFlightId: singleFlight.faFlightId, |
| 368 | ); |
| 369 | |
| 370 | if (info == null) { |
| 371 | error = 'No flight information found'; |
| 372 | panelState = FlightPanelState.idle; |
| 373 | notifyListeners(); |
| 374 | return; |
| 375 | } |
| 376 | |
| 377 | _processFlightInfo(info, iataCode, icaoCode, |
| 378 | } catch (e) { |
| 379 | if (e is DioException) { |
| 380 | error = getErrorMessage(e.response? |
| 381 | } else { |
| 382 | error = 'Failed to load flight information: $e'; |
| 383 | } |
| 384 | panelState = FlightPanelState.idle; |
| 385 | notifyListeners(); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | void handleFlightSelection(String |
| 390 | if (pendingIata == null || pendingIcao == |
| 391 | return; |
| 392 | } |
| 393 | loadFlightInfo( |
| 394 | pendingIata!, |
| 395 | pendingIcao!, |
| 396 | pendingDate!, |
| 397 | faFlightId: faFlightId, |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | void closeFlightSelection() { |
| 402 | panelState = FlightPanelState.idle; |
| 403 | flightSearchResults = null; |
| 404 | pendingIata = null; |
| 405 | pendingIcao = null; |
| 406 | pendingDate = null; |
| 407 | selectedDate = null; |
| 408 | notifyListeners(); |
| 409 | } |
| 410 | |
| 411 | Future<void> onAircraftSelected |
| 412 | FlightsControllerGetFlightsInBoundsV1200ResponseFlightsInner aircraft, |
| 413 | ) async { |
| 414 | panelState = FlightPanelState.loadingFlight; |
| 415 | error = null; |
| 416 | flightInfo = null; |
| 417 | arrivalAirport = null; |
| 418 | departureAirport = null; |
| 419 | coordinates = []; |
| 420 | flightTrackPoints = []; |
| 421 | currentPosition = null; |
| 422 | selectedDate = DateTime.now() |
| 423 | selectedAirline = null; |
| 424 | selectedFlightNumber = null; |
| 425 | flights = BuiltList.from([]) |
| 426 | notifyListeners(); |
| 427 | |
| 428 | if (aircraft.identIata?.isNotEmpty == |
| 429 | aircraft.identIcao?.isNotEmpty == true) { |
| 430 | final iata = aircraft.identIata ?? |
| 431 | final icao = aircraft.identIcao ?? |
| 432 | await loadFlightInfo( |
| 433 | iata, |
| 434 | icao, |
| 435 | selectedDate!, |
| 436 | ); |
| 437 | } else { |
| 438 | error = 'No flight identifiers available'; |
| 439 | panelState = FlightPanelState.idle; |
| 440 | notifyListeners(); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | void refreshTracking() { |
| 445 | if (flightInfo == null) return |
| 446 | stopTrackPolling(); |
| 447 | final flightNo = flightInfo!.flightNo |
| 448 | final date = flightInfo!.date |
| 449 | startTrackPolling(flightNo, flightNo, date); |
| 450 | } |
| 451 | |
| 452 | void clearFlightContext() { |
| 453 | stopTrackPolling(); |
| 454 | flightInfo = null; |
| 455 | panelState = FlightPanelState.idle; |
| 456 | arrivalAirport = null; |
| 457 | departureAirport = null; |
| 458 | coordinates = []; |
| 459 | flightTrackPoints = []; |
| 460 | currentPosition = null; |
| 461 | selectedDate = null; |
| 462 | selectedAirline = null; |
| 463 | selectedFlightNumber = null; |
| 464 | flights = BuiltList.from([]) |
| 465 | error = null; |
| 466 | flightSearchResults = null; |
| 467 | pendingIata = null; |
| 468 | pendingIcao = null; |
| 469 | pendingDate = null; |
| 470 | results = []; |
| 471 | flightController.clear(); |
| 472 | notifyListeners(); |
| 473 | } |
| 474 | |
| 475 | void stopTrackPolling() { |
| 476 | _trackPollingTimer?.cancel(); |
| 477 | _trackPollingTimer = null; |
| 478 | _countdownTimer?.cancel(); |
| 479 | _countdownTimer = null; |
| 480 | } |
| 481 | |
| 482 | void startTrackPolling(String |
| 483 | stopTrackPolling(); |
| 484 | _secondsUntilNextUpdate = 30; |
| 485 | _countdownTimer = Timer.periodic( |
| 486 | const Duration(seconds: |
| 487 | (timer) { |
| 488 | if (_secondsUntilNextUpdate > 0) { |
| 489 | _secondsUntilNextUpdate--; |
| 490 | } else { |
| 491 | _secondsUntilNextUpdate = 30; |
| 492 | } |
| 493 | notifyListeners(); |
| 494 | }, |
| 495 | ); |
| 496 | |
| 497 | _trackPollingTimer = Timer.periodic( |
| 498 | const Duration(seconds: |
| 499 | (timer) async { |
| 500 | try { |
| 501 | _secondsUntilNextUpdate = 30; |
| 502 | notifyListeners(); |
| 503 | final trackData = await retry |
| 504 | () => _flightService.getFlightTrack( |
| 505 | iata, |
| 506 | icao, |
| 507 | date: date, |
| 508 | ), |
| 509 | maxAttempts: 3, |
| 510 | delayFactor: const Duration(seconds |
| 511 | maxDelay: const Duration(seconds |
| 512 | ); |
| 513 | |
| 514 | if (trackData != null && trackData. |
| 515 | flightTrackPoints = trackData.positions |
| 516 | .map( |
| 517 | (pos) => LatLng( |
| 518 | pos.latitude.toDouble(), |
| 519 | pos.longitude.toDouble(), |
| 520 | ), |
| 521 | ) |
| 522 | .toList(); |
| 523 | flightPositions = trackData.positions; |
| 524 | currentPosition = trackData.positions.last; |
| 525 | _updateInAirStatus(currentPosition); |
| 526 | notifyListeners(); |
| 527 | if (!isInAir) { |
| 528 | stopTrackPolling(); |
| 529 | } |
| 530 | } |
| 531 | } catch (_) { |
| 532 | // keep polling even if it fails |
| 533 | } |
| 534 | }, |
| 535 | ); |
| 536 | } |
| 537 | |
| 538 | void _processFlightInfo( |
| 539 | FlightResponseEntity info, |
| 540 | String iataCode, |
| 541 | String icaoCode, |
| 542 | DateTime date, |
| 543 | ) { |
| 544 | coordinates = [ |
| 545 | LatLng( |
| 546 | info.departure.airport.location.lat. |
| 547 | info.departure.airport.location.lon. |
| 548 | ), |
| 549 | LatLng( |
| 550 | info.arrival.airport.location.lat. |
| 551 | info.arrival.airport.location.lon. |
| 552 | ), |
| 553 | ]; |
| 554 | |
| 555 | try { |
| 556 | final trackData = _flightService.getFlightTrack |
| 557 | iataCode, |
| 558 | icaoCode, |
| 559 | date: date, |
| 560 | ); |
| 561 | |
| 562 | trackData.then((track) { |
| 563 | if (track != null && track. |
| 564 | flightTrackPoints = track.positions |
| 565 | .map( |
| 566 | (pos) => LatLng( |
| 567 | pos.latitude.toDouble(), |
| 568 | pos.longitude.toDouble(), |
| 569 | ), |
| 570 | ) |
| 571 | .toList(); |
| 572 | |
| 573 | flightPositions = track.positions; |
| 574 | currentPosition = track.positions.last; |
| 575 | _updateInAirStatus(currentPosition); |
| 576 | if (isInAir) { |
| 577 | startTrackPolling(iataCode, icaoCode, date); |
| 578 | } |
| 579 | notifyListeners(); |
| 580 | } |
| 581 | }); |
| 582 | } catch (_) { |
| 583 | // ignore |
| 584 | } |
| 585 | |
| 586 | flightInfo = info; |
| 587 | panelState = FlightPanelState.showingFlight; |
| 588 | |
| 589 | // Update the widget with the fetched flight data |
| 590 | WidgetUpdateService.updateWidgetWithFlight(info).catchError |
| 591 | print('Failed to update widget: $e' |
| 592 | }); |
| 593 | |
| 594 | notifyListeners(); |
| 595 | } |
| 596 | |
| 597 | void _updateInAirStatus([FlightPositionEntity |
| 598 | final pos = latestPosition ?? currentPosition; |
| 599 | if (pos == null) { |
| 600 | isInAir = false; |
| 601 | return; |
| 602 | } |
| 603 | final ts = pos.timestamp; |
| 604 | final notPast = !_isPastFlight |
| 605 | final altitudeOk = (pos.altitude) > |
| 606 | final speedOk = (pos.groundspeed) > |
| 607 | isInAir = notPast && (altitudeOk || speedOk); |
| 608 | } |
| 609 | |
| 610 | bool _isPastFlight(dynamic |
| 611 | if (positionTimestamp == null) return |
| 612 | DateTime? ts; |
| 613 | if (positionTimestamp is DateTime) { |
| 614 | ts = positionTimestamp.toUtc(); |
| 615 | } else if (positionTimestamp is String |
| 616 | ts = DateTime.tryParse(positionTimestamp) |
| 617 | } |
| 618 | if (ts == null) return |
| 619 | final nowUtc = DateTime. |
| 620 | return nowUtc.difference(ts). |
| 621 | } |
| 622 | } |
| 623 | |