//
//  ActionTopAlertHandler.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 7/18/22.
//  Copyright © 2022 Verizon Wireless. All rights reserved.
//

import Foundation
import MVMCore

/// Creates and shows an alert using the ResponseInfo of a Page found in the cache.
open class ActionTopAlertHandler: MVMCoreActionHandlerProtocol {
    required public init() {}
    
    open func execute(with model: ActionModelProtocol, delegateObject: DelegateObject?, additionalData: [AnyHashable : Any]?) async throws {
        guard let model = model as? ActionTopAlertModel else { return }
        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
            MVMCoreCache.shared()?.fetchJSON(forPageType: model.pageType, queue: nil, waitUntilFinished: true, completionHandler: { json in
                guard let responseInfo = json?.optionalDictionaryForKey(KeyResponseInfo) else {
                    continuation.resume(throwing: ModelRegistry.Error.decoderOther(message: "Alert Page \(model.pageType) missing ResponseInfo"))
                    return
                }
                
                var alertObject = MVMCoreAlertObject(forPageType: model.pageType, responseInfo: responseInfo, additionalData: additionalData, delegateObject: delegateObject)
                if let object = alertObject,
                   let closure = (delegateObject?.actionDelegate as? MVMCoreUIActionDelegateProtocol)?.willShowTopAlert {
                    alertObject = closure(object, json!)
                }
                alertObject?.showAlert()
                continuation.resume()
            })
        }
    }
}
