//
//  MapViewModel.swift
//  Runner
//
//  Created by Groot on 2025/5/7.
//

import Flutter
import Foundation
import MapKit
import CoreLocation
import SwiftUI
import Combine

class MapViewModel: NSObject, ObservableObject, MapCapability {
    
    var paramsDecodeError: FlutterError? = FlutterError(code: "InvalidArguments", message: "Invalid arguments", details: nil)
    
    var methodChannel: FlutterMethodChannel?
    
    @Published var currentRegion: MKCoordinateRegion?
    
    // 地图Marker
    @Published var markers: [ATMapMarker] = []
    
    // 地图Polyline
    @Published var polylines: [ATMapPolyline] = []
    
    //移动至多个点的位置，并提供设置padding距离
    @Published var suitableLocation: [ATMapPolyline] = []
    
    ///禁用或开启地图所有交互
    @Published var interactionEnabled : String = ""
    
    /// 显示或隐藏地图logo
    @Published var logoVisible : String = ""
    
    // 处理地图移动
    func handleMapMoveCamera(args: [String: Any]?, result: @escaping FlutterResult) {
        guard let args = args, let cameraPosition = ATMapCameraPosition.fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        
        let center = CLLocationCoordinate2D(latitude: cameraPosition.latitude, longitude: cameraPosition.longitude)
        let zoome = cameraPosition.zoom / 10000
        let span = MKCoordinateSpan(latitudeDelta: zoome, longitudeDelta: zoome)
        
        currentRegion = MKCoordinateRegion(center: center, span: span)
        result(nil)
    }
    
    // 处理地图添加Marker
    func handleMapAddMarker(args: [[String: Any]]?, result: @escaping FlutterResult) {
    
        guard let args = args, let newMarkers = [ATMapMarker].fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        
        var markerDict = Dictionary(uniqueKeysWithValues: self.markers.map { ($0.id, $0) })
        
        for marker in newMarkers {
            markerDict[marker.id] = marker
        }
        
        self.markers = Array(markerDict.values)
        result(nil)
    }
    
    // 处理地图清除Marker
    func handleMapClearMarkers(result: @escaping FlutterResult) {
        markers = []
        result(nil)
    }
    
    // 处理地图替换所有Marker
    func handleMapReplaceAllMarkers(args: [[String: Any]]?, result: @escaping FlutterResult) {
        defer {
            result(nil)
        }
        guard let args = args, let markers = [ATMapMarker].fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        
        self.markers = markers
    }
    
    // 处理Marker点击事件
    func handleMarkerTap(marker: inout ATMapMarker) {
        toggleMarkerSelected(marker: &marker)
        methodChannel?.invokeMethod(MapViewChannelMethod.methodMarkerOnTap.rawValue, arguments: marker.toJson())
    }
    
    // 处理地图添加Polyline
    func handleMapAddPolyline(args: [String: Any]?, result: @escaping FlutterResult) {
        guard let args = args, let polyline = ATMapPolyline.fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        polylines.append(polyline)
        
        result(nil)
    }
    
    ///处理移动至多个点的位置，并提供设置padding距离
    func handleMapMoveToSuitableLocation(args: [String : Any]?, result: @escaping FlutterResult) {
        guard let args = args, let polyline = ATMapPolyline.fromJson(json: args) else {
            result(paramsDecodeError);
            return;
        }
        suitableLocation.append(polyline)
        result(nil);
    }
    
    ///清除指定标记物
    func handleMapRemovemarker(args: [String : Any]?, result: @escaping FlutterResult) {
        defer {
            result(nil)
        }
        guard let args = args, let markerItem = ATMapMarker.fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        
        // 使用标识符找到要移除的标记物并从数组中删除
        
        DispatchQueue.main.async{
            if let index = self.markers.firstIndex(where: { $0.id == markerItem.markerId }) {
                self.markers.remove(at: index)
            }
        }
    }
    
    ///清除制定的线
    func handleMapRemovePolyline(args: [String : Any]?, result: @escaping FlutterResult) {
        guard let args = args, let polyline = ATMapPolyline.fromJson(json: args) else {
            result(paramsDecodeError)
            return
        }
        DispatchQueue.main.async {
            if let index = self.polylines.firstIndex(where: { $0.lineId == polyline.lineId }) {
                self.polylines.remove(at: index)
            }
        }
        result(nil)
    }
    
    ///禁用或开启地图所有交互
    func handleMapInteractionEnabled(args: [String: Any]?, result: @escaping FlutterResult) {
        if let enabled = args?["enabled"] {
            self.interactionEnabled = "\(enabled)";
        }
        result(nil)
    }
    
    ///显示或隐藏地图logo
    func handleMapLogoVisible(args: [String : Any]?, result: @escaping FlutterResult) {
        if let visible = args?["visible"] {
            self.logoVisible = "\(visible)";
        }
        result(nil)
    }
}

// Propertie Action
extension MapViewModel {
    func toggleMarkerSelected(marker: inout ATMapMarker) {
        marker.isSelected = !marker.isSelected
    }
}
