//
//  MapViewController.swift
//  Em-call
//
//  Created by Alex Sh on 18.02.2022.
//

import UIKit
import MapKit

protocol MapViewControllerDelegate:class {
    func delegateClick(text:String)
}

class MapViewController: UIViewController {
      
    @IBOutlet weak var addressLocation: UITextField!
    @IBAction func pressSavePosition(_ sender: Any) {
        let textAddress = addressLocation.text ?? " "
        self.delegate?.delegateClick(text: textAddress)
        _  = self.navigationController?.popViewController( animated: true)
    }
    weak var delegate:MapViewControllerDelegate?
    var showAlert:ShowAlert = ShowAlert()
   
    @IBOutlet weak var mapView: MKMapView!
     let locationManager = LocationMng()
    @IBOutlet weak var textLocation: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let initialLocation = CLLocation(latitude: 51.509865, longitude: -0.118092)
       
        mapView.centerToLocation(initialLocation)
        let annotations = MKPointAnnotation()
            annotations.title = "Set my location"
            annotations.coordinate = CLLocationCoordinate2D(latitude:
                                                                51.509865, longitude: -0.118092)
            mapView.addAnnotation(annotations)

    }
    
    override func viewDidAppear(_ animated:Bool) {
        super.viewDidAppear(animated)
         locationManager.checkLocationEnable()
    }
    
    
    @IBAction func longPress(_ sender: Any) {
        let pressPoint = (sender as AnyObject).location(in:mapView)
       // let pressCoordinate = mapView.convert(pressPoint, to: mapView)
        let pressCoordinate = mapView.convert(pressPoint, toCoordinateFrom: mapView)
  
        let myposannot = MKPointAnnotation()

                myposannot.coordinate = pressCoordinate
                myposannot.title = "My place"
                myposannot.subtitle = "I am here!"
        mapView.addAnnotation(myposannot)
        
        let getLat: CLLocationDegrees = pressCoordinate.latitude
            let getLon: CLLocationDegrees = pressCoordinate.longitude
            let locationTouch: CLLocation =  CLLocation(latitude: getLat, longitude: getLon)
            coordinateToAdress(locationTouch)

    }
    
    func mapView(mapViewAnnot: MKMapView!,ViewForAnnotation annotation: MKAnnotation!) ->MKAnnotationView{
  
         let reuseId = "pin"

        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
  
         if(pinView == nil){
             pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
             pinView!.canShowCallout = true
             pinView!.animatesDrop = true
            pinView!.pinTintColor = .red
         } else {
             pinView!.annotation = annotation
         }
         return pinView!
     }
    // Преобразуем координаты в Адрес
func coordinateToAdress(_ locations: CLLocation)  {
CLGeocoder().reverseGeocodeLocation(locations /*.last!*/) { (placemarks, error) in
// Детализированная информация по точке
var placemark: CLPlacemark!

if let placemarks = placemarks {
    placemark = placemarks[0]
}
// Словарь адресов            //
 guard let country = placemark.addressDictionary!["Country"] as?
        String
 else {               // print("Country name \(country)")
    return
}
guard let city:String = (placemark.addressDictionary!["City"] as? String)
else {            //print("City name \(city)")
    return
}
guard let street = placemark.addressDictionary!["Street"] as? String
else {
    return// print(street)
}
guard let subLocality = placemark.addressDictionary!["SubLocality"] as? String
else {
    return// print(subLocality)
}
self.textLocation.text = city + " , "  + street + " , " + subLocality

}
}
    /*    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }    */
}
private extension MKMapView {
  func centerToLocation(
    _ location: CLLocation,
    regionRadius: CLLocationDistance = 1000
  ) {
    let coordinateRegion = MKCoordinateRegion(
      center: location.coordinate,
      latitudinalMeters: regionRadius,
      longitudinalMeters: regionRadius)
    setRegion(coordinateRegion, animated: true)
  }
}
