//
//  ViewController.swift
//  DisplayCurrentLocation
//
//  Created by Keith Welch on 12/6/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation
import AddressBook

class ViewController: UIViewController {

    @IBOutlet weak var txtAddress: UITextView!
    @IBOutlet weak var segType: UISegmentedControl!
    @IBOutlet weak var slideZoom: UISlider!
    @IBOutlet weak var mapView: MKMapView!
    
    var coord: CLLocationCoordinate2D!
    var locationManager:CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")))
        {
            locationManager.requestWhenInUseAuthorization()
        }
        mapView.showsUserLocation = true
    }
    
    @IBAction func btnGetMapTouched(sender: AnyObject) {
        
        let userLocation: MKUserLocation = mapView.userLocation
        coord = userLocation.location!.coordinate
        mapView.centerCoordinate = coord
        
        SetZoom()
        ReverseGeocode(userLocation.location!)
    }
    
    func SetZoom() {
        let meters: Double = (Double)(slideZoom.value * 30000)
        let region: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance (coord, meters, meters);
        
        mapView.setRegion(region, animated:false)
    }
    
    @IBAction func segTypeChanged(sender: AnyObject) {
        if (segType.selectedSegmentIndex == 0) {
            mapView.mapType = MKMapType.Standard
        }
        else {
            mapView.mapType = MKMapType.Satellite
        }
    }
    
    @IBAction func slideZoomChanged(sender: AnyObject) {
        SetZoom()
    }

    func ReverseGeocode(newLocation: CLLocation) {
        let geocoder = CLGeocoder()
        
        geocoder.reverseGeocodeLocation(newLocation, completionHandler: {(placemarks, error) -> Void in
            if (error != nil) {
                NSLog("Geocode failed with error: %@", error!)
                return
            }
            
            if((placemarks != nil) && (placemarks!.count > 0)) {
                let placemark:CLPlacemark = placemarks![0]
                let address = placemark.thoroughfare
                let city = placemark.locality
                let state = placemark.subAdministrativeArea
                let zip = placemark.postalCode
                self.txtAddress.text = String(format:"%@ %@ %@ %@", address!,city!, state!, zip!)
            }
        })
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

