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

import Foundation
import MVMCore

/// Shows an alert using the model.
open class ActionAlertHandler: MVMCoreJSONActionHandlerProtocol {
    required public init() {}
    
    open func performAction(with JSON: [AnyHashable : Any], model: ActionModelProtocol, delegateObject: DelegateObject?, additionalData: [AnyHashable : Any]?) async throws {
        var error: MVMCoreErrorObject? = nil
        guard let alertObject = MVMCoreAlertObject.alertObjectWith(action: JSON, additionalData: additionalData, delegateObject: delegateObject, error: &error) else {
            throw MVMCoreError.errorObject(error!)
        }
        (delegateObject?.actionDelegate as? MVMCoreUIActionDelegateProtocol)?.willShowPopup(with: alertObject, alertJson: JSON)
        _ = await MainActor.run {
            MVMCoreAlertHandler.shared()?.showAlert(with: alertObject)
        }
    }
    
    open func execute(with model: ActionModelProtocol, delegateObject: DelegateObject?, additionalData: [AnyHashable : Any]?) async throws {
        guard let model = model as? ActionAlertModel else { return }
        var error: MVMCoreErrorObject? = nil
        guard let alertObject = MVMCoreAlertObject.alertObject(from: model.alert, additionalData: additionalData, delegateObject: delegateObject, error: &error) else {
            throw MVMCoreError.errorObject(error!)
        }
        (delegateObject?.actionDelegate as? MVMCoreUIActionDelegateProtocol)?.willShowPopup(with: alertObject, alertJson: try MVMCoreActionHandler.convertActionToJSON(model))
        _ = await MainActor.run {
            MVMCoreAlertHandler.shared()?.showAlert(with: alertObject)
        }
    }
}
