import Foundation
import UIKit
import CoreLocation
import BaiduMapAPI_Map
import ObjectiveC

extension MapViewImpl {
    @objc public func clearCircles() {
        for (_, circle) in self.circleOverlays {
            self.mapView.remove(circle)
        }
        self.circleOverlays.removeAll()
    }

    @objc public func addCircle(
        _ latitude: Double,
        _ longitude: Double,
        _ radius: Double,
        _ strokeColor: String,
        _ fillColor: String,
        _ strokeWidth: Double
    ) -> Int {
        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        let circle = BMKCircle(center: coordinate, radius: radius)
        if let circleValue = circle {
            let overlayId = self.nextOverlayId
            self.nextOverlayId += 1
            NSLog("addCircle id=%d lat=%f lng=%f radius=%f", overlayId, latitude, longitude, radius)

            objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3001)!, strokeColor, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3002)!, fillColor, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3003)!, NSNumber(value: strokeWidth), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            self.mapView.add(circleValue)
            self.circleOverlays[overlayId] = circleValue
            return overlayId
        }
        return -1
    }

    @objc public func updateCircleStyle(
        _ overlayId: Int,
        _ lat: Double,
        _ lng: Double,
        _ radius: Double,
        _ strokeColor: String,
        _ fillColor: String,
        _ strokeWidth: Double
    ) {
        guard let circleValue = self.circleOverlays[overlayId] else {
            return
        }

        objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3001)!, strokeColor, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3002)!, fillColor, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        objc_setAssociatedObject(circleValue, UnsafeRawPointer(bitPattern: 3003)!, NSNumber(value: strokeWidth), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        circleValue.coordinate = CLLocationCoordinate2DMake(lat, lng)
        circleValue.radius = radius

        if let circleView = self.mapView.view(for: circleValue) as? BMKCircleView {
            circleView.strokeColor = self.colorFromString(strokeColor, UIColor.systemBlue)
            // circleView.fillColor = self.colorFromString(fillColor, UIColor.systemBlue.withAlphaComponent(0.2))
            circleView.lineWidth = CGFloat(strokeWidth)
        }
    }

    @objc public func removeCircle(_ overlayId: Int) {
        guard let circleValue = self.circleOverlays[overlayId] else {
            return
        }
        self.mapView.remove(circleValue)
        self.circleOverlays.removeValue(forKey: overlayId)
    }
}
