import 'dart:async';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_map/src/interface/map_trace_interface.dart';
import '../../flutter_map.dart';

class MapPlatform implements MapSDKInterface, MapTraceInterface {
  final MethodChannel _channel;

  final EventChannel _eventChannel =
      const EventChannel(MapConstants.mapLocationEventChannel);

  MapPlatform(this._channel);

  @override
  Future<String?> getPlatformName() {
    return _channel.invokeMethod<String>(MapConstants.getPlatformMapName);
  }

  @override
  Future<bool> init() async {
    try {
      bool? isSupport = await _channel.invokeMethod<bool>(MapConstants.init);
      if (isSupport == true) {
        return true;
      }
    } catch (e) {}
    return false;
  }

  @override
  void receiveLocationStream({required MapLocationListener listener}) {
    _eventChannel.receiveBroadcastStream().map((event) {
      // 显式转换为 Map<String, dynamic>
      return (event as Map).cast<String, dynamic>();
    }).listen((data) {
      MapLocation location = MapLocation.fromJson(data);
      listener.call(location);
    });
  }

  @override
  Future<void> startLocation() {
    return _channel.invokeMethod<void>(MapConstants.startLocation);
  }

  @override
  Future<List<LatLng>?> queryProcessedTrace(
      {required int lineID, required List<TraceLocation> locations}) {
    return _channel.invokeMethod(MapConstants.methodQueryProcessedTrace, {
      "lineID": lineID,
      "locations": jsonEncode(locations.map((e) => e.toJson()).toList())
    }).then((value) {
      final List<dynamic> data = jsonDecode(value);
      if (data.isEmpty) {
        return null;
      } else {
        return data.map((e) => LatLng.fromJson(e)).toList();
      }
    });
  }
}
