//
//  HTTPClient.swift
//  CareAxiom MVVM Assignment
//
//  Created by Sobhan Asim on 12/09/2021.
//

import Foundation
import Alamofire
import SwiftyJSON

typealias HttpClientSuccess = (AnyObject?) -> ()
typealias HttpClientFailure = (NSError) -> ()
typealias PhotoDownloadHandler = ((String?, Error?) -> Void)

class HTTPClient {
    
    
    func postRequest(withApi api : API  , success : @escaping HttpClientSuccess , failure : @escaping HttpClientFailure ) {
        
        let params = api.parameters
        let method = api.method
        
        var headers: HTTPHeaders{
            return ["Accept": "application/json"]
        }
        
        print(headers)
        print(api.url())
        //
        print(params ?? "")
        
        DispatchQueue.global(qos: .background).async {
            Alamofire.request(api.url(), method: method,parameters: params, encoding: URLEncoding.default , headers: headers).responseString { (response:DataResponse<String>) in
                DispatchQueue.main.async {
                    switch(response.result) {
                    case .success(_):
                        if let data = response.result.value{
                            success(data.parseJSONString as AnyObject?)
                        }
                    case .failure(_):
                        failure(response.result.error! as NSError)
                        
                    }
                }
            }
        }
    }
    
   func sendDownloadFileAsync(url: URL, completion: @escaping (PhotoDownloadHandler)) {
        if let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let destinationUrl = documentsUrl.appendingPathComponent("\(url.lastPathComponent).jpg")
            if FileManager().fileExists(atPath: destinationUrl.path) {
                completion(destinationUrl.path, nil)
            } else {
                let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
                var request = URLRequest(url: url)
                request.httpMethod = "GET"
                let task = session.dataTask(with: request, completionHandler: { data, response, error in
                    if error == nil {
                        if let response = response as? HTTPURLResponse {
                            if response.statusCode == 200 {
                                if let data = data {
                                    if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic) {
                                        completion(destinationUrl.path, error)
                                    } else {
                                        completion(destinationUrl.path, error)
                                    }
                                } else {
                                    completion(destinationUrl.path, error)
                                }
                            }
                        }
                    } else {
                        completion(destinationUrl.path, error)
                    }
                })
                task.resume()
            }
        }
    }
    
}
