//
//  SessionUploadImage.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/23.
//

import Foundation
import SwiftUI

class SessionUploadImage : ObservableObject {
    @Published var status = false
    // シングルトン宣言
    static let OnlyOne = SessionUploadImage()

    private var serverSession = ServerSession()
    private var Calling : Bool = false      // 通信中

    /**
     * メッセージ
     */
    func RequestUploadImage(_ uploadImage : ReqUploadImage ,completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "calld")
        if Calling {
            return
        }
        Calling = true

        // リクエストURLの組み立て
        let url_string : String = HttpRequestType.UploadImage.rawValue
        guard let req_url = URL(string : url_string) else {
            Calling = false
            return
        }

        let imageFileName = "itemp.jpg"
        let boundary = "----------\(UUID().uuidString)"

        var httpBody1 = "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"ShipId\"\r\n"
        httpBody1 += "\r\n"
        httpBody1 += "\(uploadImage.shipId)\r\n"
        httpBody1 += "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"MessageId\"\r\n"
        httpBody1 += "\r\n"
        httpBody1 += "\(uploadImage.messageId)\r\n"
        httpBody1 += "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"Location\"\r\n"
        httpBody1 += "\r\n"
        httpBody1 += "\(String(uploadImage.location))\r\n"
        httpBody1 += "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"From\"\r\n"
        httpBody1 += "\r\n"
        httpBody1 += "\(uploadImage.from)\r\n"
        httpBody1 += "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"FromId\"\r\n"
        httpBody1 += "\r\n"
        httpBody1 += "\(uploadImage.fromId)\r\n"
        httpBody1 += "--\(boundary)\r\n"
        httpBody1 += "Content-Disposition: form-data; name=\"files\"; filename=\"\(imageFileName)\"\r\n"
        httpBody1 += "Content-Type: image/jpeg\r\n"
        httpBody1 += "\r\n"

        var httpBody = Data()
        httpBody.append(httpBody1.data(using: .utf8)!)
        httpBody.append(uploadImage.files)

        var httpBody2 = "\r\n"
        httpBody2 += "--\(boundary)--\r\n"

        httpBody.append(httpBody2.data(using: .utf8)!)
//        let str: String = String(decoding: httpBody, as: UTF8.self)
        serverSession.postForm(boundary: boundary, req_url, httpBody, completion: completion)


//        if let postdata = serverSession.httpBody(boundary: boundary, uploadImage) {
//            serverSession.postForm(boundary: boundary, req_url, postdata, completion: completion)
//        }
//        else {
//            Calling = false
//            return
//        }
    }
}
