import SwiftUI
import MapKit

struct WorkoutMapView: UIViewRepresentable {

    let locations: [CLLocation]

    private var track: MKPolyline {
        let coordinates = locations.map { $0.coordinate }
        return .init(coordinates: coordinates,
                     count: coordinates.count)
    }

    var boundingRect: MKMapRect {
        track.boundingMapRect.extended(by: 1.2)
    }

    private var region: MKCoordinateRegion {
        .init(boundingRect)
    }

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.region = region
        mapView.delegate = context.coordinator
        mapView.addOverlay(track)
        return mapView
    }

    func updateUIView(_ view: MKMapView, context: Context) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: WorkoutMapView

        init(_ parent: WorkoutMapView) {
            self.parent = parent
        }

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.lineWidth = 4.0
            renderer.strokeColor = .systemBlue
            return renderer
        }

        private func regionDidChangeFromUserInteraction(_ mapView: MKMapView) -> Bool {
            let view = mapView.subviews[0]
            //  Look through gesture recognizers to determine whether this region change is from user interaction
            guard let gestureRecognizers = view.gestureRecognizers else {
                return false
            }
            for recognizer in gestureRecognizers {
                if recognizer.state == .began || recognizer.state == .ended {
                    return true
                }
            }
            return false
        }
    }
}

struct WorkoutMapView_Previews: PreviewProvider {
    static var previews: some View {
        WorkoutMapView(locations: [])
    }
}
