//
//  ItemDropdownEntryFieldModel.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 1/22/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

@objcMembers open class ItemDropdownEntryFieldModel: BaseItemPickerEntryFieldModel {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public override class var identifier: String { "dropDown" }
    
    public var options: [String] = []
    public var selectedIndex: Int?
    
    //--------------------------------------------------
    // MARK: - Validation
    //--------------------------------------------------
    
    public override func formFieldValue() -> AnyHashable? {
        guard enabled else { return nil }
        guard !options.isEmpty,
              let index = selectedIndex
        else { return nil }
        
        return options[index]
    }
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case options
        case selectedIndex
    }
    
    //--------------------------------------------------
    // MARK: - Initializers
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        try super.init(from: decoder)
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        
        options = try typeContainer.decode([String].self, forKey: .options)
        
        if let selectedIndex = try typeContainer.decodeIfPresent(Int.self, forKey: .selectedIndex) {
            self.selectedIndex = selectedIndex
            baseValue = options.indices.contains(selectedIndex) ? options[selectedIndex] : nil
        }
    }
    
    public override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(options, forKey: .options)
        try container.encodeIfPresent(options, forKey: .selectedIndex)
    }
}
