//
//  AlertModel.swift
//  MVMCore
//
//  Created by Suresh, Kamlesh on 7/14/20.
//  Copyright © 2020 myverizon. All rights reserved.
//

import UIKit
import MVMCore

public struct AlertButtonModel: Codable {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public var title: String
    public var action: ActionModelProtocol
    public var style: UIAlertAction.Style = .default
    public var preferred: Bool = false
    
    //--------------------------------------------------
    // MARK: - Initializer
    //--------------------------------------------------
    
    public init(_ title: String, _ action: ActionModelProtocol, style: UIAlertAction.Style = .default) {
        self.title = title
        self.action = action
        self.style = style
    }

    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case title
        case action
        case style
        case preferred
    }

    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        title = try typeContainer.decode(String.self, forKey: .title)

        if let style = try typeContainer.decodeIfPresent(String.self, forKey: .style) {
            self.style = UIAlertAction.Style(rawValue: style)
        }
        action = try typeContainer.decodeModel(codingKey: .action)
        preferred = try typeContainer.decodeIfPresent(Bool.self, forKey: .preferred) ?? false
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(style.rawValueString, forKey: .style)
        try container.encodeModel(action, forKey: .action)
        try container.encodeIfPresent(preferred, forKey: .preferred)
    }
}

public struct AlertModel: Codable, Identifiable, AlertModelProtocol {
    
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
        
    public var title: String?
    public var message: String?
    public var preferredStyle: UIAlertController.Style = .alert
    public var buttonModels: [AlertButtonModel]
    public var analyticsData: JSONValueDictionary?
    public var id: String
    
    public var delegateObject: DelegateObject?

    public var actions: [UIAlertAction] {
        get {
            buttonModels.map({ alertButtonModel in
                return alertButtonModel.generateAction(delegateObject: delegateObject)
            })
        }
    }
    
    public var preferredActionIndex: Int? {
        get {
            buttonModels.firstIndex(where: { alertButtonModel in
                return alertButtonModel.preferred
            })
        }
    }


    //--------------------------------------------------
    // MARK: - Init
    //--------------------------------------------------
    
    public init(title: String? = nil, message: String? = nil, buttonModels: [AlertButtonModel], style: UIAlertController.Style = .alert, delegateObject: DelegateObject? = nil, id: String = UUID().uuidString) {
        self.title = title
        self.message = message
        self.buttonModels = buttonModels
        self.preferredStyle = style
        self.delegateObject = delegateObject
        self.id = id
    }

    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case title
        case message
        case alertActions
        case style
        case analyticsData
        case id
    }

    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        delegateObject = try decoder.get()
        title = try typeContainer.decode(String.self, forKey: .title)
        message = try typeContainer.decode(String.self, forKey: .message)
        buttonModels = try typeContainer.decode([AlertButtonModel].self, forKey: .alertActions)
        analyticsData = try typeContainer.decodeIfPresent(JSONValueDictionary.self, forKey: .analyticsData)

        if let style = try typeContainer.decodeIfPresent(String.self, forKey: .style) {
            self.preferredStyle = UIAlertController.Style(rawValue: style)
        }
        id = try typeContainer.decodeIfPresent(String.self, forKey: .id) ?? UUID().uuidString
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(message, forKey: .message)
        try container.encodeIfPresent(buttonModels, forKey: .alertActions)
        try container.encode(preferredStyle.rawValueString, forKey: .style)
        try container.encodeIfPresent(analyticsData, forKey: .analyticsData)
        try container.encode(id, forKey: .id)
    }
}

public extension AlertButtonModel {
    func generateAction(with additionalData: [AnyHashable: Any]? = nil, delegateObject: DelegateObject? = nil, additionalHandling: ((AlertButtonModel, UIAlertAction)->())? = nil) -> UIAlertAction {
        let alertAction = UIAlertAction(title: title, style: style) { action in
            Task(priority: .userInitiated) {
                try? await (delegateObject?.actionDelegate as? ActionDelegateProtocol)?.performAction(with: self.action, additionalData: additionalData, delegateObject: delegateObject)
                additionalHandling?(self, action)
            }
        }
        return alertAction
    }
}
