//
//  GetNotificationAuthStatusBehavior.swift
//  MVMCoreUI
//
//  Created by Edayattu Salam, Nowfal on 13/04/23.
//  Copyright © 2023 Verizon Wireless. All rights reserved.
//

public protocol GetNotificationAuthStatusBehaviorConsumerProtocol {
    func consume(notificationStatus: UNAuthorizationStatus)
}

public class GetNotificationAuthStatusBehaviorModel: PageBehaviorModelProtocol {
    public class var identifier: String { "notificationAuthStatus" }
    public var shouldAllowMultipleInstances: Bool { false }
    
    public init() { }
}

public class GetNotificationAuthStatusBehavior: PageVisibilityBehavior {
    var delegate: MVMCoreUIDelegateObject?
    
    public required init(model: PageBehaviorModelProtocol, delegateObject: MVMCoreUIDelegateObject?) {
        self.delegate = delegateObject
    }
    
    public func onPageShown(_ delegateObject: MVMCoreUIDelegateObject?) {
        // Get notification auth status
        getNotificationStatus()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    @objc public func onForeground() {
        // Get notification authorization status
        getNotificationStatus()
    }
    
    public func getNotificationStatus() {
        guard let rootMolecules = self.delegate?.moleculeDelegate?.getRootMolecules() else { return }
        let consumers: [GetNotificationAuthStatusBehaviorConsumerProtocol] = rootMolecules.allMoleculesOfType()
        
        let center = UNUserNotificationCenter.current()
        center.getNotificationSettings { (settings) in
            for consumer in consumers {
                consumer.consume(notificationStatus: settings.authorizationStatus)
            }
            
            Task {
                // Tell template to update
                guard let controller = self.delegate?.moleculeDelegate as? ViewController else { return }
                await controller.handleNewData()
            }
        }
    }
    
    public func onPageHidden(_ delegateObject: MVMCoreUIDelegateObject?) {
        NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
    }
}
