// lib/services/gnss/phone_gps_connection.dart
import 'dart:async';
import 'dart:typed_data';
import 'package:geolocator/geolocator.dart';
import 'gnss_connection.dart';
import 'gnss_device_service.dart';

class PhoneGpsConnection implements GnssConnection {
  @override
  GnssConnectionType get type => GnssConnectionType.phoneGps;

  final _stateController = StreamController<GnssConnectionState>.broadcast();
  final _positionController = StreamController<Position>.broadcast();
  StreamSubscription<Position>? _positionSub;

  @override
  Stream<String> get nmeaLines => const Stream.empty(); // Nincs NMEA

  @override
  Stream<Position> get positionStream => _positionController.stream;

  @override
  Stream<GnssConnectionState> get connectionState => _stateController.stream;

  @override
  Future<void> connect(String address) async {
    _stateController.add(GnssConnectionState.connecting);

    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      _stateController.add(GnssConnectionState.error);
      return;
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        _stateController.add(GnssConnectionState.error);
        return;
      }
    }

    _stateController.add(GnssConnectionState.connected);

    // Belső GPS folyamatos olvasása
    _positionSub = Geolocator.getPositionStream(
      locationSettings: const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 0, // Folyamatos frissítés
      ),
    ).listen((Position pos) {
      _positionController.add(pos);
    });
  }

  @override
  Future<void> disconnect() async {
    await _positionSub?.cancel();
    _stateController.add(GnssConnectionState.disconnected);
  }

  @override
  void sendData(Uint8List data) {
    // A telefon beépített GPS-e nem fogad RTCM adatokat
  }

  @override
  void dispose() {
    _positionSub?.cancel();
    _positionController.close();
    _stateController.close();
  }
}
