import Foundation
import Combine

let isConsoleLoggingEnabled = false

final class LoggerMiddleware {
    #if DEBUG
        func middleware(state: ClientState, action: ClientAction) -> AnyPublisher<ClientAction, Never> {
            switch action {
            case .empty:
                return Empty().eraseToAnyPublisher()

            default:
                let timeStr = dateFormatter.string(from: Date())
                var actionStr = "\(action)"
                let ends = actionStr.count > 800 ? "..." : ""
                actionStr = String(actionStr.prefix(800)) + ends
                let str = "\(timeStr) xmpp-client \(state.jid): \(lineSymbol(action))\(actionStr)"
                print(str)
                if isConsoleLoggingEnabled {
                    NSLog(str)
                }
                return Empty().eraseToAnyPublisher()
            }
        }
    #else
        func loggerMiddleware() -> Middleware<AppState, AppAction> {
            Empty().eraseToAnyPublisher()
        }
    #endif

    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        formatter.dateFormat = "MM-dd HH:mm:ss.SSS"
        return formatter
    }

    private func lineSymbol(_ action: ClientAction) -> String {
        switch action {
        case .clientError, .streamAction(.streamError):
            return "❗"

        case .connectionAction(.connectionSend):
            return "⇢ "

        case .connectionAction(.connectionReceived):
            return "⇠ "

        default:
            return ""
        }
    }
}
