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

import Foundation
import MVMCore

/// Shows a popup alert by grabbing the content from a Page in the cache using the pageType.
open class ActionPopupHandler: MVMCoreActionHandlerProtocol {
    required public init() {}
    
    open func execute(with model: ActionModelProtocol, delegateObject: DelegateObject?, additionalData: [AnyHashable : Any]?) async throws {
        guard let model = model as? ActionPopupModel else { return }
        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
            MVMCoreCache.shared()?.fetchJSON(forPageType: model.pageType, queue: nil, waitUntilFinished: true, completionHandler: { json in
                var error: MVMCoreErrorObject? = nil
                guard let alertObject = MVMCoreAlertObject(page: json, isGreedy: false, additionalData: additionalData, delegateObject: delegateObject, error: &error) else {
                    continuation.resume(throwing: MVMCoreError.errorObject(error!))
                    return
                }
                (delegateObject?.actionDelegate as? MVMCoreUIActionDelegateProtocol)?.willShowPopup(with: alertObject, alertJson: json!)
                Task { @MainActor in
                    MVMCoreAlertHandler.shared()?.showAlert(with: alertObject)
                    continuation.resume()
                }
            })
        }
    }
}
