 //
 
 import UIKit
+import CoreLocation
 import MapKit
 
 class ViewController: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate {

    @IBOutlet weak var searchBar: UISearchBar!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.mapView.showsUserLocation = true
    }

    override func didReceiveMemoryWarning() {


    // called when keyboard search button pressed
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchBar.resignFirstResponder()

        if(!CLLocationManager.locationServicesEnabled()) {
            requestToTurnOnLocationServices()
        }

        if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined ) {
            locationManager.requestAlwaysAuthorization()
            return
        } else if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied) {
            requestToAuthorizeLocationServiceForApp()
            return
        }

        // Proceed if everything is fine
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        mapView.showsUserLocation = true
    }

    func requestToTurnOnLocationServices() {
        let alert = UIAlertController.init(title: "Location services", message: "Location services are not enabled for this device. Please enable location services in settings", preferredStyle: UIAlertControllerStyle.Alert)
        let defaultAction = UIAlertAction.init(title: "Dismiss", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in}
        alert.addAction(defaultAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }

    func requestToAuthorizeLocationServiceForApp() {
        let alert = UIAlertController.init(title: "Location services", message: "Location services are disable for this application. Please enable location services for this app in settings.", preferredStyle: UIAlertControllerStyle.Alert)
        let defaultAction = UIAlertAction.init(title: "Dismiss", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in}
        alert.addAction(defaultAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

