import Foundation
import Recording

/// A preinstalling service that records its requests, resolves the supported locales from configurable tables, and emits events
/// on demand.
@MainActor
final class PreinstallingMock: Preinstalling {
    
    // MARK: Properties

    /// The stream of events the service emits while preinstalling.
    let events: AsyncStream<PreinstallingEvent>

    /// The supported equivalents the service resolves, keyed by the requested locale.
    var equivalents: [Locale: Locale] = [:]

    /// The locales the service reports as supported.
    var localesSupported: [Locale] = []

    /// The locales a preinstallation was requested for, in request order.
    private(set) var localesPreinstalled: [Locale] = []

    /// The continuation that feeds ``events``.
    private let continuation: AsyncStream<PreinstallingEvent>.Continuation
    
    // MARK: Initializers

    init() {
        (events, continuation) = AsyncStream.makeStream(of: PreinstallingEvent.self)
    }
    
    // MARK: Methods

    /// Emits the given event through ``events``.
    ///
    /// - Parameter event: The event to emit.
    func emit(
        _ event: PreinstallingEvent
    ) {
        continuation.yield(event)
    }

    func preinstall(
        for locale: Locale
    ) async {
        localesPreinstalled.append(locale)
    }

    func supportedLocale(
        equivalentTo locale: Locale
    ) async -> Locale? {
        equivalents[locale]
    }

    func supportedLocales() async -> [Locale] {
        localesSupported
    }

}
