//
// Created by Alexander Zalutskiy on 12.08.15.
// Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import Foundation

extension Facade {
  struct AbonentSettingsNotificationNames {
    static let GetSuccess = "AbonentSettingsGetSuccess"
    static let GetError = "AbonentSettingsGetError"
    static let SetSuccess = "AbonentSettingsSetSuccess"
    static let SetError = "AbonentSettingsSetError"
  }
  
  func getAbonentSettings(onError: (error: NSError) -> Void, onSuccess: (abonentSettings: AbonentSettings) -> Void) {
    if Facade.serverId == nil || Facade.accountId == nil {
      getGuid(self.getAbonentInfo)
    } else {
      let parameters = [
        "access_token": Facade.accessToken!,
        "client_id": Facade.clientId!,
        ] as [String: AnyObject]
      
      request(.POST, "https://telecom.kz/api/guid/get_abonent_settings.json", parameters: parameters, encoding: .JSON).responseJSON(completionHandler: { (resp) in
        Router.globalLog.debug(resp.request!)
        switch resp.result {
        case .Failure(let error):
          Router.globalLog.error(error.debugDescription)
          onError(error: error)
          //					self.notificationCenter.postNotificationName(AbonentSettingsNotificationNames.GetError, object: self, userInfo: [
          //						FacadeNotificationErrorKey: error,
        //						])
        case .Success(let json):
          Router.globalLog.debug(resp.response!)
          Router.globalLog.debug(json)
          let abonentSettings = AbonentSettings(json: JSON(json as! [String : AnyObject]))
          onSuccess(abonentSettings: abonentSettings)
          //						self.notificationCenter.postNotificationName(AbonentSettingsNotificationNames.GetSuccess, object: self, userInfo: [
          //							FacadeNotificationObjectKey: abonentSettings,
          //							])
          //          } else {
          //            Router.globalLog.debug(FacadeError.ParsingObject)
          //            self.notificationCenter.postNotificationName(AbonentSettingsNotificationNames.GetError, object: self, userInfo: [
          //              FacadeNotificationErrorKey: FacadeError.ParsingObject,
          //              ])
          //          }
        }})
    }
  }
  
  func setAbonentSettings(json: JSON, onError: (error: NSError) -> Void, onSuccess: (success: String) -> Void, onHalfSuccess: (halfSuccess: String) -> Void) {
    if Facade.serverId == nil || Facade.accountId == nil {
      getGuid(self.getAbonentInfo)
    } else {
      var parameters = json.dictionaryObject!
      parameters["access_token"] = Facade.accessToken!
      parameters["client_id"] = Facade.clientId!
      
      request(.POST, "https://telecom.kz/api/guid/save_settings.json", parameters: parameters, encoding: .JSON).responseJSON(completionHandler: { (resp) in
        Router.globalLog.debug(resp.request!)
        switch resp.result {
        case .Failure(let error):
          Router.globalLog.error(error.debugDescription)
          onError(error: error)
          //					self.notificationCenter.postNotificationName(AbonentSettingsNotificationNames.SetError, object: self, userInfo: [
          //						FacadeNotificationErrorKey: error,
        //						])
        case .Success(let json):
          Router.globalLog.debug(resp.response!)
          if let success = json["success"] as? String where success == "ok" {
            onSuccess(success: success)
            //						self.notificationCenter.postNotificationName(AbonentSettingsNotificationNames.SetSuccess, object: self)
          } else {
            let error = json["error"]
            if let errorPass = error!!["new_password"] as? String{
              Router.globalLog.error(errorPass)
              onHalfSuccess(halfSuccess: errorPass)
            } else {
              onHalfSuccess(halfSuccess: error as! String)
            }
            //                        onHalfSuccess(halfSuccess: json.array[0] as! String)
          }
          
        }
      })
    }
  }
  
  func getMailNotificationList(params: [String: AnyObject], onSuccess: (emails: [String]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.GetMailNotificationList(params)).response { (req, resp, data, error) in
      onFinish()
      Router.globalLog.debug(req)
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        let json = JSON(data: data!)
        Router.globalLog.debug(resp)
        Router.globalLog.debug(json)
        if let emailsDict = json.arrayObject as? [[String: String]]{
          var emailsArray:[String] = []
          for item in emailsDict {
            emailsArray.append(item["email"]!)
          }
          onSuccess(emails: emailsArray)
        }
      }
    }
  }
  
  func mailNotification(params: [String: AnyObject], onSuccess: (msg: String) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.MailNotification(params)).response { (req, resp, data, error) in
      Router.globalLog.debug(req)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        let json = JSON(data: data!)
        Router.globalLog.debug(resp)
        Router.globalLog.debug(json)
        onSuccess(msg: json.stringValue)
      }
    }
  }
}
