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

import UIKit
import CoreLocation
import AddressBook

class ViewController: UIViewController {

    @IBOutlet weak var txtAddress: UITextView!
    @IBOutlet weak var lblLatitudeLongitude: UILabel!
    @IBOutlet weak var lblAddress: UILabel!
    var coords: CLLocationCoordinate2D!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnGeocodeTouched(sender: AnyObject) {
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(txtAddress.text, 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] 
                self.coords = placemark.location!.coordinate;
                self.lblLatitudeLongitude.text = String(format: "Latitude = %f, Longitude = %f", self.coords.latitude, self.coords.longitude)
            }
        })
    }
    
    @IBAction func btnReverseGeocodeTouched(sender: AnyObject) {
        let newLocation = CLLocation(latitude: coords.latitude, longitude: coords.longitude)
        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.lblAddress.text = String(format:"%@ %@ %@ %@", address!,city!, state!, zip!)
            }
        })

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

