import Dependencies
import Foundation
import Network

public struct NetworkMonitor {
    public var start: () -> Void
}

extension NetworkMonitor: DependencyKey {
    public static let liveValue: Self = {
        var monitor = NWPathMonitor()

        return Self(
            start: {
                monitor.pathUpdateHandler = { path in
                    NotificationCenter.default.post(
                        Notification(
                            name: reachabilityDidChangeNotification,
                            userInfo: ["status": path.status == .satisfied]
                        )
                    )
                }

                let queue = DispatchQueue(label: "Monitor")
                monitor.start(queue: queue)
            }
        )
    }()
}

extension NetworkMonitor: TestDependencyKey {
    public static let previewValue = Self.noop

    public static let testValue = Self(
        start: unimplemented("\(Self.self).start")
    )
}

public extension NetworkMonitor {
    static let noop = Self(
        start: unimplemented("\(Self.self).start")
    )
}

public let reachabilityDidChangeNotification = Notification.Name("reachabilityDidChange")
