 //  Copyright (c) 2014 Baluta Cristian. All rights reserved.
 //
 
-#if os(iOS)
-import UIKit
-#else
-import Cocoa
-#endif
+import Foundation
 
 struct RCHttpError: LocalizedError {
     var errorDescription: String?

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
		request.httpBody = jsonData
        request = authenticate(request)
		
		let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
		task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
			
            guard let httpStatus = response as? HTTPURLResponse, let data = data, error == nil else {
                print("POST \(url) -> \(error!)")
                failure(error!)
                return
            }
			print("status code = \(httpStatus.statusCode)")
//            RCLogO( NSString(data: data!, encoding: 0));

            if let d = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)  {
                success(d)
            } else {
                print("Not a valid json for url \(url)")
                failure(RCHttpError(errorDescription: "Invalid json response"))
            }
		})
		task?.resume()
	}
	
    //mark: put data sync and async
    
    func put (at path: String, parameters: [String: Any], success: @escaping (Any) -> Void, failure: @escaping (Error) -> Void) {
        
        guard baseURL != nil else {
            fatalError("URL was not set")
        }
        let fullPath = baseURL.appendingPathComponent(path).absoluteString.removingPercentEncoding!
        let url = URL(string: fullPath)!
        let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        request = authenticate(request)
        print("PUT to \(url) -> \(request)")
        
        let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
        task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
            
            guard let httpStatus = response as? HTTPURLResponse, let data = data, error == nil else {
                print("PUT to \(url) -> \(error!)")
                failure(error!)
                return
            }
            print("PUT to \(url) response: \(String(data: data, encoding: .utf8) ?? "") -> status code = \(httpStatus.statusCode)")
            success(data)
        })
        task!.resume()
    }
    
	func upload (data: Data, filename: String, completion: @escaping (NSDictionary) -> Void, error: @escaping (NSDictionary) -> Void) {
