import 'dart:async';

import 'package:dio/dio.dart';
import 'package:geolocator/geolocator.dart';

import '../constants/app_constants.dart';
import '../network/api_client.dart';
import 'offline_queue_service.dart';

class LocationReporterService {
  final ApiClient _apiClient;
  final OfflineQueueService _offlineQueue;
  Timer? _timer;

  LocationReporterService(this._apiClient, this._offlineQueue);

  Future<void> start({bool walkGuideActive = false}) async {
    await stop();
    final interval = Duration(
      milliseconds: walkGuideActive ? AppConstants.locationIntervalWalkMs : AppConstants.locationIntervalIdleMs,
    );
    await _sendOnce();
    _timer = Timer.periodic(interval, (_) => _sendOnce());
  }

  Future<void> stop() async {
    _timer?.cancel();
    _timer = null;
  }

  Future<void> _sendOnce() async {
    try {
      await Geolocator.requestPermission();
      final position = await Geolocator.getCurrentPosition();
      await _apiClient.dio.post('/user/location', data: {
        'lat': position.latitude,
        'lng': position.longitude,
        'accuracy': position.accuracy,
        'speed': position.speed,
        'heading': position.heading,
      });
    } on DioException catch (_) {
      await _offlineQueue.enqueue(OfflineRequest(
        method: 'POST',
        path: '/user/location',
        body: const {'lat': null, 'lng': null},
        createdAt: DateTime.now(),
      ));
    } catch (_) {
      // GPS permission can be unavailable during desktop/web testing.
    }
  }
}
