//
//  Facade+Cities.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 27.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import Foundation

let FacadeUpdateCities = "FacadeUpdateCities"

extension Facade {
  
  func getCities(onFinish: ((String?) -> Void)? = nil) {
    request(Router.Cities).validate(statusCode: [200]).responseSwiftyJSON {
      (req, resp, json, error) in
      Router.globalLog.debug(req)
      
      Router.globalLog.debug(json)
      if error == nil {
        Router.globalLog.debug(resp)
        CitiesManager.sharedInstance().setCities(json)
        CitiesManager.sharedInstance().saveCities()
        onFinish?(nil)
        NSNotificationCenter.defaultCenter().postNotificationName(FacadeUpdateCities, object: nil)
      } else {
        Router.globalLog.error(error.debugDescription)
        onFinish?(error?.localizedDescription)
      }
    }
  }
  
  func getCity(id: Int) {
    request(Router.City(id)).responseSwiftyJSON {
      (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      if let error = error {
        Router.globalLog.error(error.debugDescription)
      } else {
        Router.globalLog.debug(resp)
      }
    }
  }
  
  func getUserCity() {
    if (LocationManager.sharedInstance().worked) {
      LocationManager.sharedInstance().needGetUserCity = false
      let parametes = [
        "lat" : LocationManager.sharedInstance().location!.coordinate.latitude,
        "lng" : LocationManager.sharedInstance().location!.coordinate.longitude
      ]
      
      request(Router.Position(parametes)).validate(statusCode: [200]).responseSwiftyJSON {
        (req, resp, json, error) in
        Router.globalLog.debug(req)
        Router.globalLog.debug(json)
        if error == nil {
          let city = City(json: json)
          CitiesManager.sharedInstance().setUserCity(city)
          Router.globalLog.debug(resp)
        } else {
          Router.globalLog.error(error.debugDescription)
        }
      }
    }
  }
}
