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

import Flutter
import UIKit
import SwiftUI

class MapFlutterViewFactory: NSObject, FlutterPlatformViewFactory {
    private var messenger: FlutterBinaryMessenger

    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
    }

    func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
        return MapFlutterView(withFrame: frame, viewIdentifier: viewId, arguments: args, binaryMessenger: messenger)
    }

    func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
        return FlutterStandardMessageCodec.sharedInstance()
    }
}

class MapFlutterView: NSObject, FlutterPlatformView {

    var contentView: UIView

    var methodChannel: FlutterMethodChannel
    
    var viewModel: MapViewModel = .init()

    init(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?, binaryMessenger messenger: FlutterBinaryMessenger) {
        contentView = UIView()
        methodChannel = FlutterMethodChannel(name: MapKitConstans.mapViewMethodChannelName + "\(viewId)", binaryMessenger: messenger)
        super.init()
        createMapView()
        setupMethodChannel()
    }

    func view() -> UIView {
        return contentView
    }

    func createMapView() {
        let keyWindows = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first(where: { $0.isKeyWindow })
        let topController = keyWindows?.rootViewController
        
        viewModel.methodChannel = methodChannel
        let vc = MapViewController(viewModel: viewModel)
        let mapView = vc.view!
        mapView.translatesAutoresizingMaskIntoConstraints = false
        
        topController?.addChild(vc)
        contentView.addSubview(mapView)
        
        NSLayoutConstraint.activate(
            [
                mapView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
                mapView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
                mapView.topAnchor.constraint(equalTo: contentView.topAnchor),
                mapView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
            ]
        )
        
        vc.didMove(toParent: topController)
    }

    func setupMethodChannel() {
        methodChannel.setMethodCallHandler({ [weak self] (call, result) in
            self?.viewModel.handleMethodCall(call, result: result)
        })
    }
} 
