//
//  ListGroupElement.swift
//  EvidationCommonUI
//
//  Copyright © 2021 Evidation Health, Inc. All rights reserved.
//

import Foundation

/** This class should be considered a temporary arrangement (as with `ListGroupElementView`).
 It's designed to handle content as below and build suitable UX.
 ```
 {
   "family": "presentation",
   "subtype": "list_group",
   "items": [
   {
     "family": "button",
     "subtype": "action",
     "label": "Question 1 title?",
     "action": {
       "command": "get",
       "authenticate": false,
       "uri": "/v1/public/sections/1rnbzjOy5PgzTfmYNCG1OK",
       "target_identifier": "1rnbzjOy5PgzTfmYNCG1OK"
     }
   },
   ⋮
 ]
 }
 ```
 Note that the specific actions are ignored. The `target_identifier` is extracted and a `NavigationAction`
 is created. This is because at this time, the BE doesn't have the capacity to change the content.
 */
public class ListGroupElement: Element {
    public let family = "presentation"
    public let type = "list_group"
    public let id: String?
    public let layout: Layout
    public let style: ServerStyle?
    public let dynamicViewFactory: DynamicViewFactory
    public let requirements = ElementRequirements(isRequired: false, errorText: nil)
    
    public struct Row {
        let label: String
        let action:Action?
    }
    
    var rows: [Row] = []

    private init(id: String?, layout: Layout, style: ServerStyle?, dynamicViewFactory: DynamicViewFactory) {
        self.id = id
        self.layout = layout
        self.style = style
        self.dynamicViewFactory = dynamicViewFactory
    }
    
    public static func createElement(json: JSONObject, dynamicViewFactory: DynamicViewFactory) -> Element? {
        
        guard let rows = json["items"]?.array?.compactMap({ $0.dictionary })  else { return nil }
        
        let id = json["id"]?.string ?? json["identifier"]?.string
        let layout = Layout(json: json["layout"]?.dictionary)
        let style = json["style"]?.dictionary
        let element = ListGroupElement(id: id, layout: layout, style: style,
                                   dynamicViewFactory: dynamicViewFactory)
        
        rows.forEach { row in
            if let label = row["label"]?.string,
                  let actionJSON = row["action"]?.dictionary,
                  let action = dynamicViewFactory.actionFactory.create(from: actionJSON)
            {
                element.rows.append(Row(label: label, action: action))
            }
        }
        
        return element
    }
}
