//
//  MapAmapShowContentMapView.swift
//  map_amap_ios
//
//  Created by 诺诺诺的言 on 2025/7/22.
//

import UIKit
import SwiftUI
import Flutter

@available(iOS 13.0, *)
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 MapAmapShowContentMapView(withFrame: frame, viewIdentifier: viewId, arguments: args, binaryMessenger: messenger)
    }

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

@available(iOS 13.0, *)
class MapAmapShowContentMapView: NSObject, FlutterPlatformView {

    var contentView: UIView

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

    init(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?, binaryMessenger messenger: FlutterBinaryMessenger) {
        contentView = UIView()
        methodChannel = FlutterMethodChannel(name: MapAmapViewOnlyKeyword.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 = MapAmapThemeControl(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)
        })
    }
}

