import Combine
import XMPPSwift

final class RegistrationMiddleware {
    static let shared = RegistrationMiddleware()

    func middleware(state: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
        switch action {
        case .registrationAction(.targetJidChanged(let jid)):
            if state.registrationState.targetJid == jid {
                return Empty().eraseToAnyPublisher()
            } else {
                if let oldJid = state.registrationState.targetJid {
                    xmpp.doAction(.init(oldJid, .deinitClient))
                }
                return Just(.registrationAction(.targetJidUpdated(jid)))
                    .eraseToAnyPublisher()
            }

        case .registrationAction(.targetJidUpdated(let jid)):
            if let jid = jid {
                xmpp.doAction(.init(jid, .initClient))
            }
            return Empty().eraseToAnyPublisher()

        case .registrationAction(.clientStateChanged(let state)):
            switch state {
            case .loggedIn:
                return Just(AppAction.changeFlow(.chats))
                    .eraseToAnyPublisher()

            default:
                return Empty().eraseToAnyPublisher()
            }

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