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

import Foundation

let FacadeCallbackItemsSuccess = "FacadeCallbackItemsSuccess"
let FacadeCallbackRequestSuccess = "FacadeCallbackRequestSuccess"
let FacadeCallbackRequestError = "FacadeCallbackRequestError"

extension Facade {
  
  func callbackItemsForRouter(router: Router) {
    request(router).responseSwiftyJSON {
      (_, _, json, error) in
      Router.globalLog.debug(json)
      if let error = error {
        Router.globalLog.error(error.debugDescription)
      }
      var items = [CallbackPlaceProtocol]()
      
      for (index, subJson) in json {
        let text = subJson["name"].stringValue
        let id = subJson["id"].intValue
        
        switch router {
        case .CallbackServiceCities:
          items.append(CallbackCity(text: text, id: id))
        case .CallbackServiceCityAreas:
          items.append(CallbackArea(text: text, id: id))
        case .CallbackServiceCityAreaStreets:
          items.append(CallbackStreet(text: text, id: id))
        case .CallbackServiceCityAreaStreetHouses:
          items.append(CallbackHouse(text: text, id: id))
        default:
          assert(true, "WTF!!!")
        }
      }
      
      self.notificationCenter.postNotificationName(
        FacadeCallbackItemsSuccess,
        object: self,
        userInfo: ["items" : items]
      )
    }
  }
  
  func citiesForCallback() {
    request(Router.Cities).responseSwiftyJSON {
      (_, _, json, error) in
      Router.globalLog.debug(json)
      if let error = error {
        Router.globalLog.error(error.debugDescription)
      }
      
      var items = [CallbackCity]()
      
      for (index, subJson) in json {
        let text = subJson["name"].stringValue
        let id = subJson["id"].intValue
        
        items.append(CallbackCity(text: text, id: id))
      }
      
      self.notificationCenter.postNotificationName(
        FacadeCallbackItemsSuccess,
        object: self,
        userInfo: ["items" : items]
      )
    }
  }
  
  func sendCallbackRequest(cityId: Int?, serviceId: Int, fio: String, phoneNumber: String, email: String, onSuccess: () -> Void, onError: (String) -> Void, onFinish: () -> Void) {
    let parameters = [
      "name" : fio,
      "email" : email,
      "phone" : phoneNumber
    ]
    
    
    if cityId != nil {
      request(Router.SendCallbackRequest(cityId!, serviceId, parameters))
        .responseSwiftyJSON { (req, resp, json, error) in
          Router.globalLog.debug(req)
          Router.globalLog.debug(json)
          if let error = json["errors"].dictionary {
            var errorMessage: String
            if let msg = json["errors"]["email"].string {
              errorMessage = msg
            } else if let msg = json["errors"]["phone"].string {
              errorMessage = msg
            } else if let msg = json["errors"]["name"].string {
              errorMessage = msg
            } else {
              errorMessage = "Неопознанная ошибка"
            }
            Router.globalLog.error(errorMessage)
            onError(errorMessage)
          } else {
            Router.globalLog.debug(resp)
            onSuccess()
            //						self.notificationCenter.postNotificationName(FacadeCallbackRequestSuccess, object: self)
          }
      }
    } else {
      Router.globalLog.error("Поле 'Город' не может быть пустым")
      onError(LS("callback.city_error", description: "Поле \"город\" не может быть пустым"))
      //			self.notificationCenter.postNotificationName(
      //				FacadeCallbackRequestError,
      //				object: self,
      //				userInfo: ["error" : LocalizedString("callback.city_error", description: "Поле \"город\" не может быть пустым")])
    }
  }
  
}
