//
//  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 = CommonAlertView()

    public override init() {
        super.init()
        
        notificationAuthView.sureButton.setTitle("去设置", for: .normal)
        notificationAuthView.contentLabel.text = "当前应用未开启通知，建议开启"
        
        requestNotiAuthRelay
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                if let notificationAuthView = self?.notificationAuthView {
                    ENTRY.showNotificationAuthEntry(view: notificationAuthView,name: notificationAuthViewEntry)
                }
            })
            .disposed(by: disposeBag)
        
        cancelNotiAuthRelay
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { _ in
                ENTRY.dismiss(name: notificationAuthViewEntry)
            })
            .disposed(by: disposeBag)
        
        notificationAuthView.sureButton.rx.tap
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: {[weak self] _ in
                self?.openSetting()
            })
            .disposed(by: disposeBag)
        
        notificationAuthView.cancelButton.rx.tap
            .observe(on: MainScheduler.instance)
            .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)
        }
    }
}
