//
//  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, MKMapViewDelegate {
      
    @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!
    var arrayCoordMapWorker = [(51.51455283,-0.12197132),(51.5121277776,-0.120492655896),(51.515234854,-0.115117274),(51.5103413836,-0.1215190233),(51.51304096,-0.126825408),
                               (51.5089155267,-0.1272603095),
                               /*worker go*/(51.51379832395,-0.123224424264)]
    var nameImageIconMap = ["electric_map2","plumber_map2","handyman_map2","worker_map2"]
    var indexNameImageIconMap = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1.0)]
        let initialLocation = CLLocation(latitude: 51.509865, longitude: -0.118092)
        self.mapView.delegate = self
        mapView.centerToLocation(initialLocation)
        let annotations = MKPointAnnotation()
            annotations.title = "Set my location"
            annotations.coordinate = CLLocationCoordinate2D(latitude:
                                                                51.509865, longitude: -0.118092)
            mapView.addAnnotation(annotations)
 
        for coord in arrayCoordMapWorker {
            let annotations = CustomPointAnnotation()
            annotations.coordinate = CLLocationCoordinate2D(latitude:
                                                                coord.0, longitude: coord.1)
            annotations.imageName = nameImageIconMap[indexNameImageIconMap]
            
            indexNameImageIconMap = indexNameImageIconMap + 1
            if indexNameImageIconMap > 2 {
                indexNameImageIconMap = 0 }
            mapView.addAnnotation(annotations)
        }

    }
    
    
    
    override func viewDidAppear(_ animated:Bool) {
        super.viewDidAppear(animated)
         locationManager.checkLocationEnable()
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1.0)]
    }
    
    
    @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(_ mapView: MKMapView, viewFor annotation: MKAnnotation) ->MKAnnotationView? {
        if !(annotation is CustomPointAnnotation) {
             return MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
         }
         let reuseId = "pin"
        
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
                if pinView == nil {
                    pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
                    pinView?.canShowCallout = true
                }
                else {
                    pinView?.annotation = annotation
                }
  
        let cpa = annotation as! CustomPointAnnotation
        pinView!.image = UIImage(named:cpa.imageName)
  
         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)
  }
}
