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

import Alamofire
import PromiseKit

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() -> Promise<Response<T>> {
        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)
        }

        let defer = Promise<Response<T>>.defer()
        request.responseJSON(options: .AllowFragments) { (req, res, json, error) in
            managerStore.removeValueForKey(managerId)

            if let error = error {
                defer.reject(error)
                return
            }
            if res!.statusCode >= 400 {
                //TODO: Add error entity
                let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: [:])
                defer.reject(error)
                return
            }

            if () is T {
                let response = Response(response: res!, body: () as! T)
                defer.fulfill(response)
                return
            }
            if let json: AnyObject = json {
                let body = Decoders.decode(clazz: T.self, source: json)
                let response = Response(response: res!, body: body)
                defer.fulfill(response)
                return
            }
            
            defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"]))
        }
        return defer.promise
    }

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


