//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2019 Swift Server Working Group and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import NIO
import NIOHTTP1
import NIOTransportServices

public final class HTTPClientCopyingDelegate: HTTPClientResponseDelegate {
    public typealias Response = Void

    let chunkHandler: (ByteBuffer) -> EventLoopFuture<Void>

    init(chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) {
        self.chunkHandler = chunkHandler
    }

    public func didReceiveBodyPart(task: HTTPClient.Task<Void>, _ buffer: ByteBuffer) -> EventLoopFuture<Void> {
        return self.chunkHandler(buffer)
    }

    public func didFinishRequest(task: HTTPClient.Task<Void>) throws {
        return ()
    }
}

// TODO: Revisit the handling of NIO/NIOTS once https://github.com/apple/swift-nio/issues/796
// is addressed.
/// This protocol is intended as a layer of abstraction over `ClientBootstrap` and
/// `NIOTSConnectionBootstrap`.
public protocol ClientBootstrapProtocol {
    func connect(to: SocketAddress) -> EventLoopFuture<Channel>
    func connect(host: String, port: Int) -> EventLoopFuture<Channel>
    func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel>

    func connectTimeout(_ timeout: TimeAmount) -> Self
    func channelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
    func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
}

extension ClientBootstrap: ClientBootstrapProtocol {}

#if canImport(Network)
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
extension NIOTSConnectionBootstrap: ClientBootstrapProtocol {}
#endif
