| 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 | int get secondsUntilNextUpdate => _secondsUntilNextUpdate; |
| 69 | bool get isTrackingActive => |
| 70 | _trackPollingTimer != null && _trackPollingTimer!.isActive |
| 71 | |
| 72 | void initialize() { |
| 73 | loadTrackedFlights(); |
| 74 | } |
| 75 | |
| 76 | @override |
| 77 | void dispose() { |
| 78 | _controllerCleanup(); |
| 79 | flightController.dispose(); |
| 80 | super.dispose(); |
| 81 | } |
| 82 | |
| 83 | void _controllerCleanup() { |
| 84 | _debounce?.cancel(); |
| 85 | _trackPollingTimer?.cancel(); |
| 86 | _countdownTimer?.cancel(); |
| 87 | } |
| 88 | |
| 89 | void clearError() { |
| 90 | if (error != null) { |
| 91 | error = null; |
| 92 | notifyListeners(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | void debounceSearch(String |
| 97 | _debounce?.cancel(); |
| 98 | _debounce = Timer(const |
| 99 | search(query); |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | Future<void> search |
| 104 | if (query.isEmpty || query.length == |
| 105 | results = []; |
| 106 | notifyListeners(); |
| 107 | return; |
| 108 | } |
| 109 | |
| 110 | if (_cancelToken != null) { |
| 111 | _cancelToken!.cancel("User is searching for new results"); |
| 112 | } |
| 113 | _cancelToken = CancelToken(); |
| 114 | |
| 115 | searchState = SearchState.loading; |
| 116 | results = []; |
| 117 | notifyListeners(); |
| 118 | |
| 119 | try { |
| 120 | results = await _service.search(query |
| 121 | } finally { |
| 122 | searchState = SearchState.idle; |
| 123 | notifyListeners(); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | void clearSearchResults() { |
| 128 | results.clear(); |
| 129 | notifyListeners(); |
| 130 | } |
| 131 | |
| 132 | void selectAirport(AirportEntity |
| 133 | if (departureAirport == null) { |
| 134 | departureAirport = airport; |
| 135 | } else { |
| 136 | arrivalAirport = airport; |
| 137 | } |
| 138 | flightController.clear(); |
| 139 | clearSearchResults(); |
| 140 | notifyListeners(); |
| 141 | } |
| 142 | |
| 143 | void selectAirline( |
| 144 | AirlineEntity airline, { |
| 145 | String? currentInput, |
| 146 | }) { |
| 147 | selectedAirline = airline; |
| 148 | error = null; |
| 149 | final text = currentInput?.trim |
| 150 | String? remainingText; |
| 151 | final upperText = text.toUpperCase |
| 152 | final iata = airline.iata; |
| 153 | final icao = airline.icao; |
| 154 | |
| 155 | if (iata.isNotEmpty && upperText.startsWith |
| 156 | remainingText = text.substring(iata.length) |
| 157 | } else if (icao.isNotEmpty && upperText. |
| 158 | remainingText = text.substring(icao.length) |
| 159 | } else if (text.isNotEmpty && |
| 160 | airline.name.isNotEmpty && |
| 161 | upperText.contains(airline.name.toUpperCase |
| 162 | final nameIndex = upperText.indexOf |
| 163 | if (nameIndex != -1) { |
| 164 | remainingText = |
| 165 | text.substring(nameIndex + airline.name |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | if (remainingText != null && |
| 170 | remainingText.isNotEmpty && |
| 171 | RegExp(r'\d').hasMatch |
| 172 | final match = RegExp( |
| 173 | if (match != null) { |
| 174 | selectedFlightNumber = match.group(0) |
| 175 | flightController.clear(); |
| 176 | } |
| 177 | } else { |
| 178 | flightController.clear(); |
| 179 | } |
| 180 | clearSearchResults(); |
| 181 | notifyListeners(); |
| 182 | } |
| 183 | |
| 184 | void selectFlightNumber(String |
| 185 | selectedFlightNumber = flightNumber; |
| 186 | error = null; |
| 187 | flightController.clear(); |
| 188 | notifyListeners(); |
| 189 | } |
| 190 | |
| 191 | void clearAirline() { |
| 192 | selectedAirline = null; |
| 193 | error = null; |
| 194 | notifyListeners(); |
| 195 | } |
| 196 | |
| 197 | void clearFlightNumber() { |
| 198 | selectedFlightNumber = null; |
| 199 | error = null; |
| 200 | notifyListeners(); |
| 201 | } |
| 202 | |
| 203 | void clearAirports() { |
| 204 | arrivalAirport = null; |
| 205 | departureAirport = null; |
| 206 | error = null; |
| 207 | notifyListeners(); |
| 208 | } |
| 209 | |
| 210 | void clearDepartureAirport() { |
| 211 | departureAirport = null; |
| 212 | error = null; |
| 213 | notifyListeners(); |
| 214 | } |
| 215 | |
| 216 | Future<void> loadTrackedFlights |
| 217 | loadingTrackedFlights = true; |
| 218 | notifyListeners(); |
| 219 | try { |
| 220 | trackedFlights = await _flightService.getTrackedFlights() |
| 221 | } catch (_) { |
| 222 | // ignore errors for now |
| 223 | } finally { |
| 224 | loadingTrackedFlights = false; |
| 225 | notifyListeners(); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | Future<void> loadFlightsForSelection |
| 230 | selectedDate = date; |
| 231 | flights = BuiltList.from([]) |
| 232 | panelState = FlightPanelState.loadingFlight; |
| 233 | error = null; |
| 234 | notifyListeners(); |
| 235 | try { |
| 236 | if (departureAirport != null && arrivalAirport != |
| 237 | flights = await _flightService.getFlights( |
| 238 | departureAirport!.iataCode ?? departureAirport!.ident, |
| 239 | arrivalAirport!.iataCode ?? arrivalAirport!.ident, |
| 240 | date.toIso8601String(), |
| 241 | ); |
| 242 | panelState = FlightPanelState.idle; |
| 243 | } else if (selectedAirline != null && |
| 244 | await loadFlightInfo( |
| 245 | "${selectedAirline!.iata}$ |
| 246 | "${selectedAirline!.icao}$ |
| 247 | date, |
| 248 | ); |
| 249 | } |
| 250 | } catch (_) { |
| 251 | selectedDate = null; |
| 252 | panelState = FlightPanelState.idle; |
| 253 | } finally { |
| 254 | notifyListeners(); |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | Future<void> loadFlightInfo |
| 259 | String iataCode, |
| 260 | String icaoCode, |
| 261 | DateTime date, { |
| 262 | bool forceUpdate = false, |
| 263 | String? faFlightId, |
| 264 | }) async { |
| 265 | error = null; |
| 266 | panelState = FlightPanelState.loadingFlight; |
| 267 | notifyListeners(); |
| 268 | |
| 269 | try { |
| 270 | if (faFlightId != null) { |
| 271 | final info = await _flightService. |
| 272 | iataCode, |
| 273 | icaoCode, |
| 274 | date: date, |
| 275 | forceUpdate: forceUpdate, |
| 276 | faFlightId: faFlightId, |
| 277 | ); |
| 278 | |
| 279 | if (info == null) { |
| 280 | error = 'No flight information found'; |
| 281 | panelState = FlightPanelState.idle; |
| 282 | notifyListeners(); |
| 283 | return; |
| 284 | } |
| 285 | |
| 286 | _processFlightInfo(info, iataCode, icaoCode, |
| 287 | return; |
| 288 | } |
| 289 | |
| 290 | final searchResults = await _flightService. |
| 291 | iataCode, |
| 292 | icaoCode, |
| 293 | date: date, |
| 294 | ); |
| 295 | |
| 296 | if (searchResults == null || searchResults. |
| 297 | error = 'No flights found'; |
| 298 | panelState = FlightPanelState.idle; |
| 299 | notifyListeners(); |
| 300 | return; |
| 301 | } |
| 302 | |
| 303 | if (searchResults.count > 1) { |
| 304 | flightSearchResults = searchResults; |
| 305 | panelState = FlightPanelState.selectingFlight; |
| 306 | pendingIata = iataCode; |
| 307 | pendingIcao = icaoCode; |
| 308 | pendingDate = date; |
| 309 | notifyListeners(); |
| 310 | return; |
| 311 | } |
| 312 | |
| 313 | final singleFlight = searchResults.flights. |
| 314 | final info = await _flightService. |
| 315 | iataCode, |
| 316 | icaoCode, |
| 317 | date: date, |
| 318 | forceUpdate: forceUpdate, |
| 319 | faFlightId: singleFlight.faFlightId, |
| 320 | ); |
| 321 | |
| 322 | if (info == null) { |
| 323 | error = 'No flight information found'; |
| 324 | panelState = FlightPanelState.idle; |
| 325 | notifyListeners(); |
| 326 | return; |
| 327 | } |
| 328 | |
| 329 | _processFlightInfo(info, iataCode, icaoCode, |
| 330 | } catch (e) { |
| 331 | if (e is DioException) { |
| 332 | error = getErrorMessage(e.response? |
| 333 | } else { |
| 334 | error = 'Failed to load flight information: $e'; |
| 335 | } |
| 336 | panelState = FlightPanelState.idle; |
| 337 | notifyListeners(); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | void handleFlightSelection(String |
| 342 | if (pendingIata == null || pendingIcao == |
| 343 | return; |
| 344 | } |
| 345 | loadFlightInfo( |
| 346 | pendingIata!, |
| 347 | pendingIcao!, |
| 348 | pendingDate!, |
| 349 | faFlightId: faFlightId, |
| 350 | ); |
| 351 | } |
| 352 | |
| 353 | void closeFlightSelection() { |
| 354 | panelState = FlightPanelState.idle; |
| 355 | flightSearchResults = null; |
| 356 | pendingIata = null; |
| 357 | pendingIcao = null; |
| 358 | pendingDate = null; |
| 359 | selectedDate = null; |
| 360 | notifyListeners(); |
| 361 | } |
| 362 | |
| 363 | Future<void> onAircraftSelected |
| 364 | FlightsControllerGetFlightsInBoundsV1200ResponseFlightsInner aircraft, |
| 365 | ) async { |
| 366 | panelState = FlightPanelState.loadingFlight; |
| 367 | error = null; |
| 368 | flightInfo = null; |
| 369 | arrivalAirport = null; |
| 370 | departureAirport = null; |
| 371 | coordinates = []; |
| 372 | flightTrackPoints = []; |
| 373 | currentPosition = null; |
| 374 | selectedDate = DateTime.now() |
| 375 | selectedAirline = null; |
| 376 | selectedFlightNumber = null; |
| 377 | flights = BuiltList.from([]) |
| 378 | notifyListeners(); |
| 379 | |
| 380 | if (aircraft.identIata?.isNotEmpty == |
| 381 | aircraft.identIcao?.isNotEmpty == true) { |
| 382 | final iata = aircraft.identIata ?? |
| 383 | final icao = aircraft.identIcao ?? |
| 384 | await loadFlightInfo( |
| 385 | iata, |
| 386 | icao, |
| 387 | selectedDate!, |
| 388 | ); |
| 389 | } else { |
| 390 | error = 'No flight identifiers available'; |
| 391 | panelState = FlightPanelState.idle; |
| 392 | notifyListeners(); |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | void refreshTracking() { |
| 397 | if (flightInfo == null) return |
| 398 | stopTrackPolling(); |
| 399 | final flightNo = flightInfo!.flightNo |
| 400 | final date = flightInfo!.date |
| 401 | startTrackPolling(flightNo, flightNo, date); |
| 402 | } |
| 403 | |
| 404 | void clearFlightContext() { |
| 405 | stopTrackPolling(); |
| 406 | flightInfo = null; |
| 407 | panelState = FlightPanelState.idle; |
| 408 | arrivalAirport = null; |
| 409 | departureAirport = null; |
| 410 | coordinates = []; |
| 411 | flightTrackPoints = []; |
| 412 | currentPosition = null; |
| 413 | selectedDate = null; |
| 414 | selectedAirline = null; |
| 415 | selectedFlightNumber = null; |
| 416 | flights = BuiltList.from([]) |
| 417 | error = null; |
| 418 | flightSearchResults = null; |
| 419 | pendingIata = null; |
| 420 | pendingIcao = null; |
| 421 | pendingDate = null; |
| 422 | results = []; |
| 423 | flightController.clear(); |
| 424 | notifyListeners(); |
| 425 | } |
| 426 | |
| 427 | void stopTrackPolling() { |
| 428 | _trackPollingTimer?.cancel(); |
| 429 | _trackPollingTimer = null; |
| 430 | _countdownTimer?.cancel(); |
| 431 | _countdownTimer = null; |
| 432 | } |
| 433 | |
| 434 | void startTrackPolling(String |
| 435 | stopTrackPolling(); |
| 436 | _secondsUntilNextUpdate = 30; |
| 437 | _countdownTimer = Timer.periodic( |
| 438 | const Duration(seconds: |
| 439 | (timer) { |
| 440 | if (_secondsUntilNextUpdate > 0) { |
| 441 | _secondsUntilNextUpdate--; |
| 442 | } else { |
| 443 | _secondsUntilNextUpdate = 30; |
| 444 | } |
| 445 | notifyListeners(); |
| 446 | }, |
| 447 | ); |
| 448 | |
| 449 | _trackPollingTimer = Timer.periodic( |
| 450 | const Duration(seconds: |
| 451 | (timer) async { |
| 452 | try { |
| 453 | _secondsUntilNextUpdate = 30; |
| 454 | notifyListeners(); |
| 455 | final trackData = await retry |
| 456 | () => _flightService.getFlightTrack( |
| 457 | iata, |
| 458 | icao, |
| 459 | date: date, |
| 460 | ), |
| 461 | maxAttempts: 3, |
| 462 | delayFactor: const Duration(seconds |
| 463 | maxDelay: const Duration(seconds |
| 464 | ); |
| 465 | |
| 466 | if (trackData != null && trackData. |
| 467 | flightTrackPoints = trackData.positions |
| 468 | .map( |
| 469 | (pos) => LatLng( |
| 470 | pos.latitude.toDouble(), |
| 471 | pos.longitude.toDouble(), |
| 472 | ), |
| 473 | ) |
| 474 | .toList(); |
| 475 | flightPositions = trackData.positions; |
| 476 | currentPosition = trackData.positions.last; |
| 477 | _updateInAirStatus(currentPosition); |
| 478 | notifyListeners(); |
| 479 | if (!isInAir) { |
| 480 | stopTrackPolling(); |
| 481 | } |
| 482 | } |
| 483 | } catch (_) { |
| 484 | // keep polling even if it fails |
| 485 | } |
| 486 | }, |
| 487 | ); |
| 488 | } |
| 489 | |
| 490 | void _processFlightInfo( |
| 491 | FlightResponseEntity info, |
| 492 | String iataCode, |
| 493 | String icaoCode, |
| 494 | DateTime date, |
| 495 | ) { |
| 496 | coordinates = [ |
| 497 | LatLng( |
| 498 | info.departure.airport.location.lat. |
| 499 | info.departure.airport.location.lon. |
| 500 | ), |
| 501 | LatLng( |
| 502 | info.arrival.airport.location.lat. |
| 503 | info.arrival.airport.location.lon. |
| 504 | ), |
| 505 | ]; |
| 506 | |
| 507 | try { |
| 508 | final trackData = _flightService.getFlightTrack |
| 509 | iataCode, |
| 510 | icaoCode, |
| 511 | date: date, |
| 512 | ); |
| 513 | |
| 514 | trackData.then((track) { |
| 515 | if (track != null && track. |
| 516 | flightTrackPoints = track.positions |
| 517 | .map( |
| 518 | (pos) => LatLng( |
| 519 | pos.latitude.toDouble(), |
| 520 | pos.longitude.toDouble(), |
| 521 | ), |
| 522 | ) |
| 523 | .toList(); |
| 524 | |
| 525 | flightPositions = track.positions; |
| 526 | currentPosition = track.positions.last; |
| 527 | _updateInAirStatus(currentPosition); |
| 528 | if (isInAir) { |
| 529 | startTrackPolling(iataCode, icaoCode, date); |
| 530 | } |
| 531 | notifyListeners(); |
| 532 | } |
| 533 | }); |
| 534 | } catch (_) { |
| 535 | // ignore |
| 536 | } |
| 537 | |
| 538 | flightInfo = info; |
| 539 | panelState = FlightPanelState.showingFlight; |
| 540 | |
| 541 | // Update the widget with the fetched flight data |
| 542 | WidgetUpdateService.updateWidgetWithFlight(info).catchError |
| 543 | print('Failed to update widget: $e' |
| 544 | }); |
| 545 | |
| 546 | notifyListeners(); |
| 547 | } |
| 548 | |
| 549 | void _updateInAirStatus([FlightPositionEntity |
| 550 | final pos = latestPosition ?? currentPosition; |
| 551 | if (pos == null) { |
| 552 | isInAir = false; |
| 553 | return; |
| 554 | } |
| 555 | final ts = pos.timestamp; |
| 556 | final notPast = !_isPastFlight |
| 557 | final altitudeOk = (pos.altitude) > |
| 558 | final speedOk = (pos.groundspeed) > |
| 559 | isInAir = notPast && (altitudeOk || speedOk); |
| 560 | } |
| 561 | |
| 562 | bool _isPastFlight(dynamic |
| 563 | if (positionTimestamp == null) return |
| 564 | DateTime? ts; |
| 565 | if (positionTimestamp is DateTime) { |
| 566 | ts = positionTimestamp.toUtc(); |
| 567 | } else if (positionTimestamp is String |
| 568 | ts = DateTime.tryParse(positionTimestamp) |
| 569 | } |
| 570 | if (ts == null) return |
| 571 | final nowUtc = DateTime. |
| 572 | return nowUtc.difference(ts). |
| 573 | } |
| 574 | } |
| 575 | |