//
//  NetworkOperation.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 04.06.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class NetworkOperation : ConcurrentOperation {
  
  // define properties to hold everything that you'll supply when you instantiate
  // this object and will be used when the request finally starts
  //
  // in this example, I'll keep track of (a) URL; and (b) closure to call when request is done
  
  let urlRequest: URLRequestConvertible
  let networkOperationCompletionHandler: (NSURLRequest?, NSHTTPURLResponse?, JSON, NSError?) -> ()
  
  // we'll also keep track of the resulting request operation in case we need to cancel it later
  
  weak var someRequest: Request?
  
  // define init method that captures all of the properties to be used when issuing the request
  
  init(urlRequest: URLRequestConvertible, networkOperationCompletionHandler: (NSURLRequest?, NSHTTPURLResponse?, JSON, NSError?) -> ()) {
    self.urlRequest = urlRequest
    self.networkOperationCompletionHandler = networkOperationCompletionHandler
    super.init()
  }
  
  // when the operation actually starts, this is the method that will be called
  
  override func main() {
    self.someRequest = request(self.urlRequest).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      //      if let error = error {
      //        onError(error.localizedDescription)
      //      }
      //    self.someRequest = request(.GET, URLString, parameters: ["foo": "bar"])
      //      .responseJSON { response in
      // do whatever you want here; personally, I'll just all the completion handler that was passed to me in `init`
      
      self.networkOperationCompletionHandler(req, resp, json, error)
      
      // now that I'm done, complete this operation
      
      self.completeOperation()
    })
  }
  
  // we'll also support canceling the request, in case we need it
  
  override func cancel() {
    someRequest?.cancel()
    super.cancel()
  }
}
