// AlamofireImplementations.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//

import Alamofire

class AlamofireRequestBuilderFactory: RequestBuilderFactory {
    func getBuilder<T>() -> RequestBuilder<T>.Type {
        return AlamofireRequestBuilder<T>.self
    }
}

// Store manager to retain its reference
private var managerStore: [String: Alamofire.Manager] = [:]

class AlamofireRequestBuilder<T>: RequestBuilder<T> {
    required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) {
        super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody)
    }

    override func execute(completion: (response: Response<T>?, erorr: NSError?) -> Void) {
        let managerId = NSUUID().UUIDString
        // Create a new manager for each request to customize its request header
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.HTTPAdditionalHeaders = buildHeaders()
        let manager = Alamofire.Manager(configuration: configuration)
        managerStore[managerId] = manager

        let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL
        let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding)
        if let credential = self.credential {
            request.authenticate(usingCredential: credential)
        }

        request.responseJSON(options: .AllowFragments) { (req, res, json, error) in
            managerStore.removeValueForKey(managerId)

            if let error = error {
                completion(response: nil, erorr: error)
                return
            }
            if res!.statusCode >= 400 {
                //TODO: Add error entity
                let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:]
                let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo)
                completion(response: nil, erorr: error)
                return
            }

            if () is T {
                let response = Response(response: res!, body: () as! T)
                completion(response: response, erorr: nil)
                return
            }
            if let json: AnyObject = json {
                let body = Decoders.decode(clazz: T.self, source: json)
                let response = Response(response: res!, body: body)
                completion(response: response, erorr: nil)
                return
            } else if "" is T {
                // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release
                // https://github.com/swagger-api/swagger-parser/pull/34
                let response = Response(response: res!, body: "" as! T)
                completion(response: response, erorr: nil)
                return
            }
            
            completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))
        }
    }

    private func buildHeaders() -> [String: AnyObject] {
        var httpHeaders = Manager.defaultHTTPHeaders
        for (key, value) in self.headers {
            httpHeaders[key] = value
        }
        return httpHeaders
    }
}

