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

import UIKit
import CoreLocation
import MapKit
import AddressBook

class ViewController: UIViewController {

    @IBOutlet weak var txtFromAddress: UITextField!
    @IBOutlet weak var txtToAddress: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func btnGetDirectionsTouched(sender: AnyObject) {
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(txtFromAddress.text!, completionHandler: {(placemarks, error) -> Void in
            if (error != nil) {
                NSLog("Geocode failed with error: %@", error!)
                return
            }
            if((placemarks != nil) && (placemarks!.count > 0)) {
                let geocodedFromPlacemark:CLPlacemark = placemarks![0]
                let fromPlacemark = MKPlacemark(placemark: geocodedFromPlacemark)

                geocoder.geocodeAddressString(self.txtToAddress.text!, completionHandler: {(placemarks, error) -> Void in
                    if (error != nil) {
                        NSLog("Geocode failed with error: %@", error!)
                        return
                    }
                    if((placemarks != nil) && (placemarks!.count > 0)) {
                        let geocodedToPlacemark:CLPlacemark = placemarks![0]
                        let toPlacemark = MKPlacemark(placemark: geocodedToPlacemark)

                        // Create a map item for the geocoded address to pass to Maps app
                        let fromMapItem = MKMapItem(placemark: fromPlacemark)
                        fromMapItem.name = geocodedFromPlacemark.name

                        let toMapItem = MKMapItem(placemark: toPlacemark)
                        toMapItem.name = geocodedToPlacemark.name
                        
                        // Set the directions mode to "Driving"
                        let launchOptions = [
                            MKLaunchOptionsDirectionsModeKey:
                            MKLaunchOptionsDirectionsModeDriving]
                        
                        // Pass the current location and destination map items to the Maps app
                        // Set the direction mode in the launchOptions dictionary
                        MKMapItem.openMapsWithItems([fromMapItem, toMapItem],launchOptions: launchOptions)
                        
                    }
                })
            }
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

