//
//  QSLHomeAnnotatinView.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/6.
//

import UIKit
import MAMapKit

class QSLHomeAnnotatinView: MAAnnotationView {

    var title: String?
    var calloutView: MapLocationCalloutView?

    override func setSelected(_ selected: Bool, animated: Bool) {
        if self.isSelected == selected {
            return
        }
        
        if selected {
            if calloutView == nil {
                let width = (title?.widthAccording(height: 20.rpx, font: UIFont.textM(14), lineSpacing: 0) ?? 0)
                calloutView = MapLocationCalloutView(frame: CGRect(x: 0, y: 0, width: width + 32.rpx, height: 20.rpx))
                if let calloutView = calloutView {
                    calloutView.center = CGPoint(x: bounds.size.width / 2 + calloutOffset.x,
                                                 y: -calloutView.bounds.size.height / 2 + calloutOffset.y)
                }
            }
            calloutView?.name = title
            if let calloutView = calloutView {
                addSubview(calloutView)
            }
        } else {
            calloutView?.removeFromSuperview()
        }

        super.setSelected(selected, animated: animated)
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        var view = super.hitTest(point, with: event)
        if view == nil {
            let convertedPoint = convert(point, from: self)
            if bounds.contains(convertedPoint) {
                view = self
            }
        }
        return view
    }
}
