//
//  Facade+Cash+Payment.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 19.05.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation

extension Facade {
    
    func createOrder(params: [String: AnyObject], onSuccess: (data: NSData) -> Void, onError: ((error: String) -> Void), onFinish: () -> Void) {
        request(Router.CreateOrder(params)).responseData { (resp) in
            Router.globalLog.debug(resp.request!)
            onFinish()
            if let error = resp.result.error {
                Router.globalLog.error(error.debugDescription)
                onError(error: error.localizedDescription)
            } else {
                let json = JSON(data: resp.data!)
                Router.globalLog.debug(resp.response!)
                Router.globalLog.debug(json)
                if let errorCode = json["error_code"].int, let errorMsg = json["error"].string where errorCode != 0 {
                    Router.globalLog.error("errorCode: \(errorCode), errorMsg: \(errorMsg)")
                    onError(error: errorMsg)
                } else {
                    onSuccess(data: resp.data!)
                }
            }
        }
    }
    
    func getBalance(phoneNumber: String, onSuccess: ((Int) -> Void)? = nil, onError: ((NSError) -> Void)? = nil) {
        if Facade.accessToken == nil || Facade.clientId == nil {
            notificationCenter.postNotification(UserNeedAuthNotification)
            return
        }
        
        let params = [
            "type":"phone",
            "phone":phoneNumber,
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!
        ]
        
        request(.POST, "https://telecom.kz/api/guid/get_balance.json", parameters: params, encoding: .JSON).responseJSON { (resp) in
            Router.globalLog.debug(resp.request!)
            switch resp.result {
            case .Failure(let error):
                Router.globalLog.error(error.debugDescription)
                onError?(error)
            case .Success(let json):
                Router.globalLog.debug(resp.response!)
                Router.globalLog.debug(json)
                let balanceDouble = json["balance"] as? Double
                //let errorCode = (json["error_code"] as AnyObject)
                if (balanceDouble != nil) {
                    //let balanceDouble = json["balance"] as? Double
                    onSuccess?(lround(ceil(balanceDouble!)))
                } else {
                    onError!(NSError(domain: "", code: 1, userInfo: nil))
                }
            }
        }
    }
}


