//
//  SpinnerElement.swift
//  Pascal
//
//  Created by Gilbert Lo on 9/30/19.
//  Copyright © 2019 Evidation Health, Inc. All rights reserved.
//

import Foundation

public class SpinnerElement: Element {
    public let family = "presentation"
    public let type = "spinner"
    public let id: String?
    public let layout: Layout
    public let style: ServerStyle?
    public var dynamicViewFactory: DynamicViewFactory
    public let requirements = ElementRequirements(isRequired: false, errorText: nil)
    
    public var handlesLoading: Bool {
        return true
    }
    
    // Define the spinner type/style
    let definition: SpinnerDefinition
    // Action to run when showing spinner
    let action: JSONObject?
    // Content to show after the action is successful
    let content: [JSONObject]?
    
    private init(definition: SpinnerDefinition, action: JSONObject?, content: [JSONObject]?,
                 id: String?, layout: Layout, style: ServerStyle?,
                 dynamicViewFactory: DynamicViewFactory) {
        self.id = id
        self.layout = layout
        self.style = style
        self.dynamicViewFactory = dynamicViewFactory
        self.definition = definition
        self.action = action
        self.content = content
    }
    
    public static func createElement(json: JSONObject, dynamicViewFactory: DynamicViewFactory) -> Element? {
        guard
            let definitionJson = json["definition"]?.dictionary,
            let definition = SpinnerDefinition(json: definitionJson) else { return nil }
        
        let id = json["id"]?.string ?? json["identifier"]?.string
        let layout = Layout(json: json["layout"]?.dictionary)
        let style = json["style"]?.dictionary
        let action = json["action"]?.dictionary
        let content = json["content"]?.array?.compactMap { $0.dictionary }
        
        let element = SpinnerElement(definition: definition, action: action, content: content,
                                     id: id, layout: layout, style: style,
                                     dynamicViewFactory: dynamicViewFactory)
        return element
    }
    
}
