import Combine
import Foundation

// MARK: Private action processing
extension XMPPService {
    func _doAction(_ action: Action) {
        switch action.type {
        case .initClient:
            let client = XMPPClient(jid: action.jid, updateCallback: clientUpdated)
            clients[action.jid] = client
            feed.send(.init(jid: action.jid, eventType: .clientInitialised))

        case .deinitClient:
            clients.removeValue(forKey: action.jid)
            // TODO: check that client disappears from memory

        case .connectToServer:
            guard let client = clients[action.jid] else {
                feed.send(.init(jid: action.jid, eventType: .serviceError(.unknownClient)))
                return
            }
            client.reconnect()

        case .login(let password):
            guard let client = clients[action.jid] else {
                feed.send(.init(jid: action.jid, eventType: .serviceError(.unknownClient)))
                return
            }
            client.loginWith(password)
        }
    }
}
