import Foundation
import UIKit
import DGis

/// Per-marker bridge: one instance per map marker. Holds the DGis.Marker and exposes update methods.
/// Created by DGisMapViewBridge.addMarker; ownership stays with the Obj-C MarkerView.
@objcMembers
public final class DGisMarkerViewBridge: NSObject {

    /// Opaque marker ID (for tap callback matching). Same as used in map's internal storage.
    public let markerId: String

    private let marker: DGis.Marker
    private let sdk: DGis.Container
    private let onRemove: () -> Void

    init(markerId: String, marker: DGis.Marker, sdk: DGis.Container, onRemove: @escaping () -> Void) {
        self.markerId = markerId
        self.marker = marker
        self.sdk = sdk
        self.onRemove = onRemove
        super.init()
    }

    // MARK: - Updates

    public func updatePosition(lat: Double, lng: Double) {
        let position = DGis.GeoPointWithElevation(
            latitude: DGis.Latitude(value: lat),
            longitude: DGis.Longitude(value: lng)
        )
        DispatchQueue.main.async { [weak self] in
            self?.marker.position = position
        }
    }

    public func updateIcon(image: UIImage) {
        guard let dgisImage = try? sdk.imageFactory.make(image: image) else { return }
        DispatchQueue.main.async { [weak self] in
            self?.marker.icon = dgisImage
        }
    }

    public func updateOpacity(opacity: Float) {
        DispatchQueue.main.async { [weak self] in
            self?.marker.iconOpacity = DGis.Opacity(value: opacity)
        }
    }

    public func updateWidth(width: Float) {
        DispatchQueue.main.async { [weak self] in
            self?.marker.iconWidth = DGis.LogicalPixel(value: width)
        }
    }

    public func updateAnchor(x: Float, y: Float) {
        DispatchQueue.main.async { [weak self] in
            self?.marker.anchor = DGis.Anchor(x: x, y: y)
        }
    }

    /// Removes this marker from the map. Call when the marker view is unmounted.
    public func remove() {
        onRemove()
    }
}
