//
//  Body.swift
//  Pachyderm
//
//  Created by Shadowfacts on 9/8/18.
//  Copyright © 2018 Shadowfacts. All rights reserved.
//

import Foundation

enum Body {
    case parameters([Parameter]?)
    case formData([Parameter]?, FormAttachment?)
    case empty
}

extension Body {
    private static let boundary: String = "PachydermBoundary"
    
    var data: Data? {
        switch self {
        case let .parameters(parameters):
            return parameters?.urlEncoded.data(using: .utf8)
        case let .formData(parameters, attachment):
            var data = Data()
            parameters?.forEach { param in
                guard let value = param.value else { return }
                data.append("--\(Body.boundary)\r\n")
                data.append("Content-Disposition: form-data; name=\"\(param.name)\"\r\n\r\n")
                data.append("\(value)\r\n")
            }
            if let attachment = attachment {
                data.append("--\(Body.boundary)\r\n")
                data.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(attachment.fileName)\"\r\n")
                data.append("Content-Type: \(attachment.mimeType)\r\n\r\n")
                data.append(attachment.data)
                data.append("\r\n")
            }
            
            data.append("--\(Body.boundary)--\r\n")
            return data
        case .empty:
            return nil
        }
    }
    
    var mimeType: String? {
        switch self {
        case let .parameters(parameters):
            if parameters == nil {
                return nil
            }
            return "application/x-www-form-urlencoded; charset=utf-8"
        case let .formData(parameters, attachment):
            if parameters == nil && attachment == nil {
                return nil
            }
            return "multipart/form-data; boundary=\(Body.boundary)"
        case .empty:
            return nil
        }
    }
}