//
//  NavigationDefinition.swift
//  Pascal
//
//  Created by Helena McGahagan on 4/19/19.
//  Copyright © 2019 Evidation Health, Inc. All rights reserved.
//

import Foundation

/// Defines the content in the navigation bar
public struct NavigationDefinition: Codable, Hashable {
    public let title: String?
    public let rightButtons: [NavigationButtonDefinition]
    /// Typically the left buttons are handled automatically by the
    ///  navigation controller (with the standard back button appearing
    ///  if there is a navigation stack)
    /// Defining an empty array will remove the navigation stack and no back button will be shown
    /// Defining anything else will also remove the navigation stack and show the defined buttons
    public let leftButtons: [NavigationButtonDefinition]?
    
    /// Optionally define a number between 0-1 indicating the progress
    /// Can be used, e.g., to display a progress bar
    public let progress: Double?
    /// Optionally define showing the steps on the progress bar
    public let progressSteps: Int?
    
    public let hideNavigationBar: Bool // Default is false
    public let hideTabBar: Bool // Default is false
    
    public static let defaultRightButtonJson: [JSONObject] = [["label": "Close", "action": ["command": "close"]]]
    
    public static func navigationDefinition(from json: JSONObject?) -> NavigationDefinition {
        let navigationTitle = json?["title"]?.string
        let rightButtonJson = json?["right"]?.array?.compactMap { $0.dictionary }
        let defaultJson = (rightButtonJson == nil) ? defaultRightButtonJson : []
        let rightButtons: [NavigationButtonDefinition]? = (rightButtonJson ?? defaultJson).compactMap {json in
            return NavigationButtonDefinition(json: json)
        }
        let leftButtonJson = json?["left"]?.array?.compactMap { $0.dictionary }
        let leftButtons: [NavigationButtonDefinition]? = leftButtonJson?.compactMap {json in
            return NavigationButtonDefinition(json: json)
        }
        let progress = json?["progress"]?.double
        let progressSteps = json?["progress_steps"]?.int
        let hideNavigationBar = json?["hide_nav_bar"]?.bool ?? false
        let hideTabBar = json?["hide_tab_bar"]?.bool ?? false
        return NavigationDefinition(title: navigationTitle, rightButtons: rightButtons ?? [], leftButtons: leftButtons,
                                    progress: progress, progressSteps: progressSteps, hideNavigationBar: hideNavigationBar, hideTabBar: hideTabBar)
    }
}

