//
//  MessageCount.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/18.
//

import Foundation
import RxRelay
import RxSwift

public let MCOUNT = MessageCount.default

open class MessageCount : NSObject {
    public static let `default` = MessageCount()
    private let disposeBag = DisposeBag()
    private let reloadToDoMessageCountRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    public var messageCountRelay = ReplayRelay<Int>.create(bufferSize: 1)
    public var pendingCountRelay = ReplayRelay<Int>.create(bufferSize: 1)
    
    public override init() {
        super.init()
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Notification_reloadRescusControolerToDoMessageCount), object: nil, queue: .main) {[weak self] note in
            self?.reloadToDoMessageCountRelay.accept(nil)
        }
    
        reloadToDoMessageCountRelay
            .flatMapLatest { _ in
                return RQ.toDoMessageCount()
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] response in
                if response?.success == true {
                    if let messageCount = response?.data?.messageCount {
                        self?.messageCountRelay.accept(messageCount)
                    }
                    if let toDoCount = response?.data?.toDoCount {
                        self?.pendingCountRelay.accept(toDoCount)
                    }
                }else{
                    
                }
            })
            .disposed(by: disposeBag)
    }
}
