import Combine
import Foundation

// MARK: Private client state handling
typealias XMPPClientUpdateMsg = (state: ClientState, action: ClientAction)
extension XMPPService {
    func clientUpdated(_ upd: XMPPClientUpdateMsg) {
        switch upd.action {
        case .clientError(let err):
            handleClientError(upd, err)

        case .connectionAction(.tlsStarted):
            feed.send(.init(jid: upd.state.jid, eventType: .serverConnectionEstablished))

        case .authAction(.gotAuthResult(let result)):
            switch result {
            case .authorized:
                feed.send(.init(jid: upd.state.jid, eventType: .clientAuthResult(authorized: true)))

            case .failed:
                feed.send(.init(jid: upd.state.jid, eventType: .clientAuthResult(authorized: false)))

            default:
                break
            }

        default:
            break
        }
    }
}

extension XMPPService {
    func handleClientError(_ upd: XMPPClientUpdateMsg, _ error: ClientError) {
        switch error {
        case .srvTimeout, .srvSocketError, .conInitError, .conTlsError:
            feed.send(.init(jid: upd.state.jid, eventType: .serviceError(.serverConnectionFailed)))

        default:
            break
        }
    }
}
