//
//  MVMCoreAlertHandler+Extension.swift
//  MVMCore
//
//  Created by Scott Pfeil on 9/15/20.
//  Copyright © 2020 myverizon. All rights reserved.
//

import Foundation

public extension MVMCoreAlertHandler {

    /// Re-evaluates the queue operations
    @objc func reevaluteQueue() {
        var highestReadyOperation: MVMCoreTopAlertOperation?
        var executingOperation: MVMCoreTopAlertOperation?
        for case let operation as MVMCoreTopAlertOperation in topAlertQueue.operations {
            guard !operation.isCancelled,
                  !operation.isFinished else { continue }
            if operation.isReady,
               highestReadyOperation == nil || operation.queuePriority.rawValue > highestReadyOperation!.queuePriority.rawValue {
                highestReadyOperation = operation
            }
            if operation.isExecuting {
                executingOperation = operation
            }
        }
        guard let currentOperation = executingOperation else { return }
        
        // Cancel the executing operation if it is no longer ready to run. Re-add for later if it is persistent.
        guard currentOperation.isReady else {
            currentOperation.reAddAfterCancel = currentOperation.topAlertObject.persistent
            currentOperation.cancel()
            return
        }
            
        // If the highest priority operation is not executing, and the executing operation is persistent, cancel it.
        if let newOperation = highestReadyOperation,
           currentOperation != newOperation,
           currentOperation.topAlertObject.persistent {
            currentOperation.reAddAfterCancel = true
            currentOperation.cancel()
        }
    }
    
    /// Registers to know when pages change.
    @objc func registerForPageChanges() {
        MVMCoreNavigationHandler.shared()?.addDelegate(self)
    }
}

extension MVMCoreAlertHandler: MVMCorePresentationDelegateProtocol {
    // Update displayable for each top alert operation when page type changes, in top queue priority order.
    public func navigationController(_ navigationController: UINavigationController, displayedViewController viewController: UIViewController) {
        guard navigationController == MVMCoreUISplitViewController.main()?.navigationController  else { return }
        let pageType = (viewController as? MVMCoreViewControllerProtocol)?.pageType
        topAlertQueue.operations.compactMap {
           $0 as? MVMCoreTopAlertOperation
        }.sorted {
            $0.queuePriority.rawValue > $1.queuePriority.rawValue
        }.forEach {
           $0.updateDisplayable(byPageType: pageType)
        }
        reevaluteQueue()
    }
}

