//
//  MapAnnotationMarkerImageView.swift
//  Pods
//
//  Created by Groot on 2025/5/14.
//

import UIKit

class MapAnnotationMarkerImageView: UIView {
    let markerType: any MapMarkerSupportType
    var isSelected: Bool = false {
        didSet {
            if oldValue != isSelected {
                updateImage()
            }
        }
    }

    private let imageView = UIImageView()

    init(markerType: any MapMarkerSupportType) {
        self.markerType = markerType
        super.init(frame: .zero)
        setupImageView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupImageView() {
        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(imageView)
        
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: topAnchor),
            imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
            imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
        
        updateImage()
    }
    
    private func updateImage() {
        imageView.image = uiImage
    }

    private var uiImage: UIImage? {
        let imageName = markerType.imageName(selected: isSelected)
        
        if let image = UIImage(named: imageName) {
            return image
        }
        
        // 尝试从插件资源束加载
        let bundleURL = Bundle(for: MapAnnotationView.self).url(forResource: "map_mapkit_ios_resources", withExtension: "bundle")
        if let bundleURL = bundleURL, let resourceBundle = Bundle(url: bundleURL) {
            return UIImage(named: imageName, in: resourceBundle, compatibleWith: nil)
        }
        
        return nil
    }
    
    ///加载网络图片
    public func loadNetworkImage(imageUrl : String) {
        // 异步加载图片
        ImageLoader.shared.loadAvatarAsync(
            from: URL(string: imageUrl)!,
            style: .circle
        ) { image, error in
            if let image = image {
                self.imageView.image = image
            }
        }
    }
}
