import Combine
import Foundation

// MARK: Service class
public final class XMPPService: ObservableObject {
    public static let shared = XMPPService()
    var clients: [JID: XMPPClient] = [:]

    public init() {}

    public private(set) var feed = PassthroughSubject<Event, Never>()

    public func doAction(_ action: Action) {
        _doAction(action)
    }
}

// MARK: Incoming actions
public extension XMPPService {
    enum ActionType {
        case initClient
        case deinitClient
        case connectToServer
        case login(_ password: String)
    }

    struct Action {
        let jid: JID
        let type: ActionType

        public init(_ jid: JID, _ action: ActionType) {
            self.jid = jid
            type = action
        }
    }
}

// MARK: Outgoing events
public extension XMPPService {
    enum EventType {
        case serviceError(ServiceError)
        case clientInitialised
        case serverConnectionEstablished
        case clientAuthResult(authorized: Bool)
    }

    struct Event {
        public let jid: JID
        public let eventType: EventType
    }
}

// MARK: Outgoing errors
public extension XMPPService {
    enum ServiceError: Error, Stateable {
        case unknownClient
        case serverConnectionFailed
    }
}
