//
//  StreamPostRequest.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/10.
//

import Foundation

// 定义一个用于处理流式响应的回调闭包类型
typealias StreamResponseHandler = (Data) -> Void
typealias CompletionHandler = (Error?) -> Void

class StreamPostRequest {
    private let url: URL
    private var request: URLRequest
    private var session: URLSession
    private let streamHandler: StreamResponseHandler
    private let completionHandler: CompletionHandler
    private var task: URLSessionDataTask?

    // 初始化方法，接收请求 URL、参数、流式响应处理闭包和完成处理闭包
    init(url: URL, parameters: [String: Any]?, streamHandler: @escaping StreamResponseHandler, completionHandler: @escaping CompletionHandler) {
        self.url = url
        self.streamHandler = streamHandler
        self.completionHandler = completionHandler

        // 创建 URLRequest 对象
        request = URLRequest(url: url)
        request.httpMethod = "POST"

        // 设置请求体（如果有）
        if let parameters = parameters {
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            } catch {
                print("Error encoding parameters: \(error)")
            }
        }

        // 创建 URLSession 并设置代理
        let delegate = StreamDelegate(streamHandler: streamHandler, completionHandler: completionHandler)
        session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
    }

    // 启动请求的方法
    func startRequest() {
        task = session.dataTask(with: request)
        task?.resume()
    }

    // 停止请求的方法
    func stopRequest() {
        task?.cancel()
    }
}

// 自定义的 URLSessionDataDelegate 类
private class StreamDelegate: NSObject, URLSessionDataDelegate {
    private let streamHandler: StreamResponseHandler
    private let completionHandler: CompletionHandler

    init(streamHandler: @escaping StreamResponseHandler, completionHandler: @escaping CompletionHandler) {
        self.streamHandler = streamHandler
        self.completionHandler = completionHandler
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        // 调用流式响应处理闭包
        streamHandler(data)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        // 调用完成处理闭包
        completionHandler(error)
    }
}

