//  OpenHaystack – Tracking personal Bluetooth devices via Apple's Find My network
//
//  Copyright © 2021 Secure Mobile Networking Lab (SEEMOO)
//  Copyright © 2021 The Open Wireless Link Project
//
//  SPDX-License-Identifier: AGPL-3.0-only

import Cocoa
import MapKit

final class MapViewController: NSViewController, MKMapViewDelegate {
    @IBOutlet weak var mapView: MKMapView!
    var pinsShown = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.mapView.delegate = self
    }

    func addLocationsReports(from devices: [FindMyDevice]) {
        if !self.mapView.annotations.isEmpty {
            self.mapView.removeAnnotations(self.mapView.annotations)
        }

        // Zoom to first location
        if let location =  devices.first?.decryptedReports?.first {
            let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
            let span = MKCoordinateSpan(latitudeDelta: 5.0, longitudeDelta: 5.0)
            let region = MKCoordinateRegion(center: coordinate, span: span)

            self.mapView.setRegion(region, animated: true)
        }

        // Add pins
        for device in devices {

            guard let reports = device.decryptedReports else {continue}
            for report in reports {
                let pin = MKPointAnnotation()
                pin.title = device.deviceId
                pin.coordinate = CLLocationCoordinate2D(latitude: report.latitude, longitude: report.longitude)
                self.mapView.addAnnotation(pin)
            }
        }

    }

    func changeMapType(_ mapType: MKMapType) {
        self.mapView.mapType = mapType
    }
}
