//
//  GMNetworkingBase.swift
//  Pods
//
//  Created by wangyang on 16/5/30.
//
//

import Foundation

/**
 *  将 responseObject 映射为 GMResponse，用泛型来指定 data 字段所对应的数据类型，参考GMNetworking.request方法的注释
 * 
 * GMResponse 的设计是依赖于后端所有接口都返回了固定的格式：肯定都含有message, data, error字段
 */
public struct GMResponse<T> {
    /// error字段为0时，该值才为true
    public var isSuccess: Bool {
        return error == 0
    }
    /// isSuccess 为 false 时可以使用该值查看错误信息
    public var failure: NSError?

    // 当 isSuccess为true时，可以安全的使用下面三个属性
    public var message: String = ""
    public var data: T!
    public var error: Int = -1

    public var errorCode: Int = -1
    public var errorExtra: T!

    /// 服务端返回的数据。如果请求还没有到达就结束了，此时值为nil
    public let responseData: Data?

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

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

    public init(responseData: Data?, request: URLRequest, response: HTTPURLResponse?) {
        self.responseData = responseData
        self.request = request
        self.response = response
    }
}

/// 只是试试 CustomStringConvertible 是否能为我们的调试带来一些便捷，结论：没有显著提高！！！
extension GMResponse: CustomStringConvertible {
    public var description: String {
        var desc = ""
        if let responseDesc = response?.description {
            desc += "\(responseDesc)"
        }

        if let jsonData = responseData,
            let json = (try? JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves)) as? Dictionary<String, Any> {
            desc += "\(json.description)"
        }

        return desc
    }
}



public enum GMUploadMimetype: String {
    case audio = "audio/aac"
    case image = "image/jpeg"

    public func param() -> [String: String] {
        switch self {
        case .audio:
            return ["type": "audio"]
        case .image:
            return ["type": "image"]
        }
    }
}

@objc public enum GMHTTPMethod: Int {
    case get     = 0
    case post    = 1
    case delete  = 2
    case put     = 3
    case options = 4
    case patch   = 5
    case head    = 6
    case trace   = 7
    case connect = 8
}

public extension GMHTTPMethod {
    public var string: String {
        switch self {
        case .options:
            return "OPTIONS"
        case .get:
            return "GET"
        case .head:
            return "HEAD"
        case .post:
            return "POST"
        case .put:
            return "PUT"
        case .patch:
            return "PATCH"
        case .delete:
            return "DELETE"
        case .trace:
            return "TRACE"
        case .connect:
            return "CONNECT"
        }
    }
}
