//
//  GMNetworkingOC.swift
//  Pods
//
//  Created by wangyang on 2017/4/27.
//
//

import Foundation
import Alamofire

@objcMembers
public class GMResponseOC: NSObject {
    /// error字段为0时，该值才为true
    public var isSuccess: Bool {
        return error == 0
    }

    /// isSuccess 为 false 时可以使用该值查看错误信息
    public var failure: NSError?

    // 当 isSuccess为true时，可以安全的使用下面三个属性
    public var message: String = ""
    /// 鉴于服务器极少接口（因为历史原因用不到data字段）没有返回data字段，所以data的确有可能是nil
    /// 但也可以放心，本来这些特殊接口的业务也用不到data字段，那么不用就不会crash
    public var data: AnyObject!
    public var error: Int = -1

    public var errorCode: Int = -1
    public var errorExtra: AnyObject!
    
    /// 服务端返回的数据。如果请求还没有到达就结束了，此时值为nil
    public var responseData: Data?

    /// The URL request sent to the server.
    public var request: URLRequest

    /// 如果在构建URLRequest时就发生了错误，那么reponse当然为nil
    public var response: HTTPURLResponse?

    public init(response: GMResponse<Any>) {
        self.responseData = response.responseData
        self.request = response.request
        self.response = response.response
        self.message = response.message
        if response.data != nil {
             self.data = response.data as AnyObject
        }
        self.error = response.error
        self.failure = response.failure
        if response.errorExtra != nil {
            self.errorExtra = response.errorExtra as AnyObject
        }
        self.errorCode = response.errorCode
    }
}


public extension GMNetworking {

    /// 在Objective-C中使用该方法请求api
    @objc public static func requestOC(api: String,
                               method: GMHTTPMethod,
                               parameters: [String: Any]?,
                               completion: ((GMResponseOC) -> Void)?) {
        GMNetworking.request(api, method, parameters) { (response: GMResponse<Any>) in
            let ocResponse = GMResponseOC(response: response)
            completion?(ocResponse)
        }
    }

    /// 在Objective-C中使用该方法请求自定义URLRequest
    @objc public static func sendOC(_ customRequest: URLRequest, completion: ((GMResponseOC) -> Void)? = nil) {
        let _ = send(customRequest) { (response: GMResponse<Any>) in
            let ocResponse = GMResponseOC(response: response)
            completion?(ocResponse)
        }
    }
    @objc public static func sendOCBack(_ customRequest: URLRequest, completion: ((GMResponseOC) -> Void)? = nil) -> URLSessionTask? {
        let dataRequest = send(customRequest) { (response: GMResponse<Any>) in
            let ocResponse = GMResponseOC(response: response)
            completion?(ocResponse)
        }
        return dataRequest.task
    }
}
