//
//  MVMCoreAlertObject+Swift.swift
//  MVMCore
//
//  Created by Suresh, Kamlesh on 7/10/20.
//  Copyright © 2020 myverizon. All rights reserved.
//


public extension MVMCoreAlertObject {
    
    @objc static func alertObjectWith(action actionJson: [AnyHashable: Any]?, additionalData: [AnyHashable: Any]?, delegateObject: DelegateObject?, error: AutoreleasingUnsafeMutablePointer<MVMCoreErrorObject?>?) -> MVMCoreAlertObject? {
        
        guard let alertJson = actionJson?.optionalDictionaryForKey("alert"),
            (alertJson.optionalStringForKey(KeyTitle) != nil || alertJson.optionalStringForKey(KeyMessage) != nil),
            let actionsList = alertJson.optionalArrayForKey("alertActions") as? [[AnyHashable: Any]]
            else {
                error?.pointee = MVMCoreErrorObject(title: nil, message: MVMCoreGetterUtility.hardcodedString(withKey: HardcodedErrorUnableToProcess), code: ErrorCode.popupFailed.rawValue, domain: ErrorDomainNative, location: String(describing: self))
                return nil
        }
        
        var actionsForAlert: [UIAlertAction] = []
        
        for actionJson in actionsList {
            let style = UIAlertAction.Style(rawValue: actionJson.stringForkey("style"))
            let alertAction = UIAlertAction(title: actionJson.optionalStringForKey(KeyTitle), style: style) { action in
                MVMCoreActionHandler.shared()?.handleAction(with: actionJson.optionalDictionaryForKey("action"),
                                                            additionalData: additionalData,
                                                            delegateObject: delegateObject)
            }
            actionsForAlert.append(alertAction)
        }
        
        let alertObject = MVMCoreAlertObject(popupAlertWithTitle: alertJson.optionalStringForKey(KeyTitle),
                                             message: alertJson.optionalStringForKey(KeyMessage),
                                             actions: actionsForAlert,
                                             isGreedy: false)
        
        if let alertStyle = alertJson.optionalStringForKey("style") {
            alertObject?.alertStyle = UIAlertController.Style(rawValue: alertStyle)
        }
        
        if let analyticsData = alertJson.optionalDictionaryForKey("analyticsData") {
            alertObject?.pageJson = ["analyticsData": analyticsData]
        }
        
        return alertObject
    }
}
