import Foundation
import Combine
import Network
import WebRTC

final class CallMiddleware {
    private var client: WebRTCClient?
    private var callback: StoreCallback?

    func setCallback(_ callback: @escaping StoreCallback) {
        self.callback = callback
    }

    func middleware(state: ClientState, action: ClientAction) -> AnyPublisher<ClientAction, Never> {
        switch action {
        case .callAction(.startCall):
            return Just(ClientAction.externalServiceAction(.startDiscoveryExternalServices))
                .eraseToAnyPublisher()

        case .externalServiceAction(.externalServicesListUpdated):
            let rtcServers = state.externalServicesState.externalServices.compactMap({ $0.asRTCIceServer() })
            client = WebRTCClient(servers: rtcServers)
            client?.delegate = self
            return Just(ClientAction.callAction(.startRTCClient))
                .eraseToAnyPublisher()

        case .callAction(.startRTCClient):
            client?.start()
            return Empty().eraseToAnyPublisher()

        default:
            return Empty().eraseToAnyPublisher()
        }
    }
}

extension CallMiddleware: WebRTCClientDelegate {
    func didObtainSdp(sdp: VoipSession) {
        callback?(ClientAction.callAction(.sdpSessionUpdated(sdp)))
    }

    func didDiscoverLocalCandidate(candidate: RTCIceCandidate) {
        print(candidate)
    }
}
