//
//  NotificationAuthTool.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/22.
//

import Foundation
import RxSwift
import RxRelay
import RxCocoa

public let NOTIAUTHTOOL = NotificationAuthTool.default

open class NotificationAuthTool : NSObject {
    public static let `default` = NotificationAuthTool()
    public let requestNotiAuthRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    public let cancelNotiAuthRelay = ReplayRelay<Any?>.create(bufferSize: 1)
    private let disposeBag = DisposeBag()
    public let notificationAuthView = NotificationAuthView()

    public override init() {
        super.init()
        
        requestNotiAuthRelay
            .subscribe(onNext: {[weak self] _ in
                if let notificationAuthView = self?.notificationAuthView {
                    ENTRY.showNotificationAuthEntry(view: notificationAuthView,name: notificationAuthViewEntry)
                }
            })
            .disposed(by: disposeBag)
        
        cancelNotiAuthRelay
            .subscribe(onNext: { _ in
                ENTRY.dismiss(name: notificationAuthViewEntry)
            })
            .disposed(by: disposeBag)
        
        notificationAuthView.setButton.rx.tap
            .subscribe(onNext: {[weak self] _ in
                self?.openSetting()
            })
            .disposed(by: disposeBag)
        
        notificationAuthView.ignoreButton.rx.tap
            .subscribe(onNext: { _ in
                ENTRY.dismiss(name: notificationAuthViewEntry)
            })
            .disposed(by: disposeBag)
    }
    
    
    public func openSetting() {
        let url = URL(string: UIApplication.openSettingsURLString)!
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
}
