//
//  ViewController.swift
//  RemoteService
//
//  Created by Keith Welch on 11/14/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    // go to http://www.wunderground.com/weather/api/d/docs?MR=1 for API details
    var WundergroundKey = "YOUR_KEY_HERE"
    
    @IBOutlet weak var lblWeather: UILabel!
    @IBOutlet weak var lblTemperature: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    @IBAction func btnGetWeatherTouched(sender: AnyObject) {
        
        GetWeatherForLocation(42.9047, longitude: 72.2100)
    }
    
    func GetWeatherForLocation(latitude: Double, longitude: Double) {
        
        let urlString = String(format: "https://api.wunderground.com/api/%@/conditions/q/%+f,%+f.json", WundergroundKey, latitude, longitude)
        
        let url:NSURL = NSURL(string: urlString)!
        
        let weatherData: NSData = NSData(contentsOfURL: url)!
        
        do {
            let weatherResults: NSDictionary = try (NSJSONSerialization.JSONObjectWithData(weatherData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary)!
            if let response : NSDictionary = weatherResults["response"] as? NSDictionary
            {
                if let errorDictionary : NSDictionary = response["error"] as? NSDictionary
                {
                    NSLog("Error reported by weather service")
                }
                else if let currentObservation : NSDictionary = weatherResults["current_observation"] as? NSDictionary
                {
                    lblTemperature.text = String(format: "Temperature: %@", currentObservation["temperature_string"] as! String)
                    lblWeather.text = String(format: "Weather: %@", currentObservation["weather"] as! String)
                }
                
            }
            
        }
        catch let error as NSError {
            NSLog(error.description)
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

