import Foundation
import Combine
import UIKit

enum UNAppStateStatus {
    case appWillResignActive
    case appDidBecomeActive
}

protocol UNAppStateServicing {
    var appStateStatusPublisher: AnyPublisher<UNAppStateStatus, Never> { get }
}

class UNAppStateService: UNAppStateServicing {
    static let shared = UNAppStateService()

    private let appStateStatusSubject = PassthroughSubject<UNAppStateStatus, Never>()
    private var cancellables = Set<AnyCancellable>()


    var appStateStatusPublisher: AnyPublisher<UNAppStateStatus, Never> {
        return appStateStatusSubject.eraseToAnyPublisher()
    }

    private init() {
        NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
            .sink { [weak self] _ in
                self?.appStateStatusSubject.send(UNAppStateStatus.appWillResignActive)
            }
            .store(in: &cancellables)

        NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
            .sink { [weak self] _ in
                self?.appStateStatusSubject.send(UNAppStateStatus.appDidBecomeActive)
            }
            .store(in: &cancellables)
    }
}
