//
//  TabsModel.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 1/13/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import UIKit

public class TabsModel: MoleculeModelProtocol {
    public static var identifier: String = "tabs"
    public var backgroundColor: Color?
    public var tabs: [TabItemModel]
    public var selectedColor = Color(uiColor: .black)
    
    // Must be capped to 0...(tabs.count - 1)
    public var selectedIndex: Int = 0
    
    private enum CodingKeys: String, CodingKey {
        case tabs
        case backgroundColor
        case selectedColor
        case selectedIndex
        case moleculeName
    }
    
    public init(with tabs: [TabItemModel]) {
        self.tabs = tabs
    }
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        tabs = try typeContainer.decode([TabItemModel].self, forKey: .tabs)
        backgroundColor = try typeContainer.decodeIfPresent(Color.self, forKey: .backgroundColor)
        if let color = try typeContainer.decodeIfPresent(Color.self, forKey: .selectedColor) {
            selectedColor = color
        }
        if let index = try typeContainer.decodeIfPresent(Int.self, forKey: .selectedIndex) {
            selectedIndex = index
        }
    }
              
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encode(tabs, forKey: .tabs)
        try container.encode(backgroundColor, forKey: .backgroundColor)
        try container.encode(selectedColor, forKey: .selectedColor)
        try container.encode(selectedIndex, forKey: .selectedIndex)
    }
}



public class TabItemModel: Codable {
    var label: LabelModel
    var action: ActionModelProtocol?
    
    init(label: LabelModel) {
        self.label = label
    }
    
    private enum CodingKeys: String, CodingKey {
        case label
        case action
    }
    
    func setDefaults() {
        if label.textAlignment == nil {
            label.textAlignment = .center
        }
    }
    
    public init(with label: LabelModel, action: ActionModelProtocol?) {
        self.label = label
        self.action = action
        setDefaults()
    }
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        label = try typeContainer.decode(LabelModel.self, forKey: .label)
        action = try typeContainer.decodeModelIfPresent(codingKey: .action)
        setDefaults()
    }
              
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encodeModel(label, forKey: .label)
        try container.encodeModelIfPresent(action, forKey: .action)
    }
}
