//
//  ViewController.swift
//  RegionAndMapType
//
//  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!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func btnGetMapTouched(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.coord = placemark.location!.coordinate
                
                self.mapView.centerCoordinate = placemark.location!.coordinate
                self.SetZoom()
            }
        })
    }
    
    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()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

