import 'package:flutter_map/flutter_map.dart';
import 'package:location/socket/atmob_location_client.dart';
import '../../utils/atmob_log.dart';

class MapHelper {
  MapHelper._();

  static const String tag = "FlutterMapHelper";

  static MapLocation? _lastLocation;

  static final List<MapLocationListener> _locationListeners = [];

  static Future<void> init() async {
    await FlutterMap.init();
    _initLocationClient(); 
  }

  static void _initLocationClient() {
    AtmobLocationClient atmobLocationClient =
        AtmobLocationClient.getAtmobLocationClient();
    FlutterMap.receiveLocationStream(listener: (location) {
      AtmobLog.d(tag, "onLocationChanged: $location");
      if (location.errorCode == 0) {
        _lastLocation = location;
        atmobLocationClient.uploadLocation(location);
        try {
          for (MapLocationListener listener in _locationListeners) {
            listener.call(location);
          }
        } catch (e) {
          AtmobLog.e(tag, "onLocationChanged error: $e");
        }
      }
    });
  }

  static Future<void> startLocation() {
    return FlutterMap.startLocation();
  }

  static MapLocation? getLastLocation() {
    return _lastLocation;
  }

  static void addLocationListener(MapLocationListener listener) {
    _locationListeners.add(listener);
  }

  static void removeLocationListener(MapLocationListener listener) {
    _locationListeners.remove(listener);
  }
}
