//
//  AlamofireSwiftyJSON.swift
//  AlamofireSwiftyJSON
//
//  Created by Pinglin Tang on 14-9-22.
//  Copyright (c) 2014 SwiftyJSON. All rights reserved.
//

import Foundation


// MARK: - Request for Swift JSON
let myConcurrentQueue = dispatch_queue_create("com.cnoon.manager-response-queue", DISPATCH_QUEUE_CONCURRENT)

extension Request {
	
	/**
	Adds a handler to be called once the request has finished.
	
	:param: queue The queue on which the completion handler is dispatched.
	:param: options The JSON serialization reading options. `.AllowFragments` by default.
	:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
	
	:returns: The request.
	*/
  
	public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self {
		return response(queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options)) { (resp) in
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        switch resp.result {
        case .Success(let object):
          var responseJSON: JSON
          responseJSON = JSON(object)
          
          dispatch_async(queue ?? dispatch_get_main_queue(), {
            completionHandler(self.request, self.response, responseJSON, nil)
          })
        case .Failure(let error):
          let responseJSON: JSON
          if let data = resp.data {
            responseJSON = JSON(data: data)
          } else {
            responseJSON = JSON.null
          }
          dispatch_async(queue ?? dispatch_get_main_queue(), {
            completionHandler(self.request, self.response, responseJSON, error)
          })
          
        }
      })
    }
	}
  
  public func responseSwiftyData(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
    return response(queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options)) { (resp) in
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        switch resp.result {
        case .Success(let data):
          dispatch_async(queue ?? dispatch_get_main_queue(), {
            completionHandler(self.request, self.response, data as! NSData, nil)
          })
        case .Failure(let error):
          dispatch_async(queue ?? dispatch_get_main_queue(), {
            completionHandler(self.request, self.response, nil, error)
          })
          
        }
      })
    }
  }
  
}


