//
//  FlockeConnector.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 29.10.18.
//  Copyright © 2018 Julian-Steffen Müller. All rights reserved.
//

import Foundation

class FlockeConnector {
    let flockeURL : URL?
    let bodyDict : NSDictionary?
    let requestType : String
    let completionHandler : (Data?, URLResponse?, Error?) -> Void
    
    init(url : String, requestType : String = "GET", bodyDict : NSDictionary?, _ completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
        self.flockeURL = URL.init(string: url)
        self.bodyDict = bodyDict
        self.requestType = requestType
        self.completionHandler = completionHandler
    }
    
    func doRequest() {
        guard let url = self.flockeURL else {
            print("DO Request: Creating URL fails")
            return
        }
    
        
        do {
            let requestBodyJSON = try JSONSerialization.data(withJSONObject: self.bodyDict!)
        
            var req = URLRequest.init(url: url)
            req.httpMethod = self.requestType
            req.httpBody = requestBodyJSON
            req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        
            URLSession.shared.dataTask(with: req, completionHandler: self.completionHandler).resume()
        }catch {
            print("Cannot convert to JSON")
            return
        }
    }
}
