import Flutter
import UIKit

enum MapSupportedPackage: String {
    case traceLocation1 = "com.shishi.dingwei"
}

var currentPackage: MapSupportedPackage {
    if let bundleId = Bundle.main.bundleIdentifier {
        if bundleId.hasPrefix(MapSupportedPackage.traceLocation1.rawValue) {
            return .traceLocation1
        }
    }
    return .traceLocation1
}

public class MapMapkitIosPlugin: NSObject, FlutterPlugin {

    public static func register(with registrar: FlutterPluginRegistrar) {
        let factory = MapFlutterViewFactory(messenger: registrar.messenger())
        registrar.register(factory, withId: MapKitConstans.mapViewId, gestureRecognizersBlockingPolicy: FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded)

        // 注册通用方法通道
        CommonMethodChannelHandler.shared.setBinaryMessenger(binaryMessenger: registrar.messenger())
        let commonMethodChannel = FlutterMethodChannel(name: MapKitConstans.commonMethodChannelName, binaryMessenger: registrar.messenger())
        commonMethodChannel.setMethodCallHandler { (call, result) in
            CommonMethodChannelHandler.shared.handleMethodCall(call: call, result: result)
        }
    }

    
}

class CommonMethodChannelHandler: NSObject {
    private var binaryMessenger: FlutterBinaryMessenger?

    static let shared = CommonMethodChannelHandler()

    private override init() {
        super.init()
    }

    func setBinaryMessenger(binaryMessenger: FlutterBinaryMessenger) {
        LocationManager.shared.initChannel(withMessenger: binaryMessenger)
        self.binaryMessenger = binaryMessenger
    }

    func handleMethodCall(call: FlutterMethodCall, result: @escaping FlutterResult) {
        handleCommonMethodCall(call: call, result: result)
    }

    private func handleCommonMethodCall(call: FlutterMethodCall, result: @escaping FlutterResult) {
         guard let callMethod = CommonChannelMethod(rawValue: call.method) else {
            result(FlutterMethodNotImplemented)
            return
        }

        switch callMethod {
        case .`init`:
            result(true)
            handleStartLocation(result: result)
        case .getPlatformMapName:
            result("map_mapkit_ios")
        case .startLocation:
            handleStartLocation(result: result)
        }
    }
    
    private func handleStartLocation(result: @escaping FlutterResult) {
        guard let binaryMessenger else { return }
        let isSuccess = LocationManager.shared.start(withMessenger: binaryMessenger)
        if !isSuccess {
            result(FlutterError(code: "LocationPermissionError", message: "Location permission not granted", details: nil))
            return
        }
    }
    
}
