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

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    
    @IBOutlet weak var lblLatitude: UILabel!
    @IBOutlet weak var lblLongitude: UILabel!
    @IBOutlet weak var txtAddress: UITextView!
    @IBOutlet weak var lblDistance: UILabel!

    var locationManager:CLLocationManager!
    var fromLocation: CLLocation!
    var toLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
}

    @IBAction func btnGetCurrentLocationTouched(sender: AnyObject) {
        if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")))
        {
            locationManager.requestWhenInUseAuthorization()
        }
        locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        fromLocation = locations.last!
        lblLatitude.text = String(format: "Latitude = %+.6f", fromLocation.coordinate.latitude)
        lblLongitude.text = String(format: "Longitude = %+.6f", fromLocation.coordinate.longitude)
    }

    @IBAction func btnGetDistance(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.toLocation = placemark.location
                
                let distanceBetween: CLLocationDistance = self.toLocation.distanceFromLocation(self.fromLocation)
                
                self.lblDistance.text = String(format: "%f miles", 0.000621371 * distanceBetween)
            }
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

