//
//  MultiItemDropdownEndryField.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 2/9/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

import UIKit


open class MultiItemDropdownEntryField: BaseItemPickerEntryField {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    /// Datasource of the picker view.
    open var pickerComponents: [[String]] {
        dropdownModel?.components ?? [[]]
    }
    
    public var dropdownModel: MultiItemDropdownEntryFieldModel? {
        model as? MultiItemDropdownEntryFieldModel
    }
    
    /// The number of components available
    public var componentCount: Int {
        pickerComponents.count
    }
    
    //--------------------------------------------------
    // MARK: - Initializers
    //--------------------------------------------------
    
    @objc public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    @objc public convenience init() {
        self.init(frame: .zero)
    }
    
    @objc required public init?(coder: NSCoder) {
        fatalError("MultiItemDropdownEntryField init(coder:) has not been implemented")
    }
    
    required public init(model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.init(model: model, delegateObject, additionalData)
    }
    
    //--------------------------------------------------
    // MARK: - Methods
    //--------------------------------------------------
    
    /// Sets the textField with the first value of the available picker data.
    @objc private func setInitialValueFromPicker() {
        
        guard setInitialValueInTextField,
              !pickerComponents.isEmpty,
              let rowText = dropdownModel?.selectedRowText
        else { return }
        
        // Update observing function and update text UI.
        observeDropdownChange?(text, rowText)
        text = rowText
        
        // Set row index value of selected component.
        for component in 0..<componentCount {
            let pickerIndex = pickerView.selectedRow(inComponent: component)
            dropdownModel?.selectedIndexes[component] = pickerIndex
        }
    }
    
    func pickerHasComponent(_ index: Int) -> Bool {
        !pickerComponents.isEmpty && !pickerComponents[index].isEmpty
    }
    
    //--------------------------------------------------
    // MARK: - TextField Observation
    //--------------------------------------------------
    
    /// Observing action of the textfield for initial interaction with the picker.
    @objc override func startEditing() {
        super.startEditing()
        
        setInitialValueFromPicker()
    }
    
    /// Observing action for when the user has ended inputting with the picker.
    @objc override func endInputing() {
        super.endInputing()
        
        guard !pickerComponents.isEmpty,
              let rowText = dropdownModel?.selectedRowText
        else { return }
        
        // update observing function with most recent selection.
        observeDropdownSelection?(rowText)
    }
    
    //--------------------------------------------------
    // MARK: - MoleculeViewProtocol
    //--------------------------------------------------
    
    public override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        
        guard let model = model as? MultiItemDropdownEntryFieldModel else { return }
        
        // Select initial rows if selectedIndexes retains value.
        for (component, row) in model.selectedIndexes {
            self.pickerView.selectRow(row, inComponent: component, animated: false)
            self.pickerView(pickerView, didSelectRow: row, inComponent: component)
        }
    }

    //--------------------------------------------------
    // MARK: - Picker Delegate
    //--------------------------------------------------
    
    @objc public override func numberOfComponents(in pickerView: UIPickerView) -> Int { componentCount }
    
    @objc public override func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        pickerComponents[component].count
    }
    
    @objc public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        guard pickerHasComponent(component) else { return nil }
        
        return pickerComponents[component][row]
    }
    
    @objc public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        guard pickerHasComponent(component) else { return }
        
        let oldText = text
        dropdownModel?.selectedIndexes[component] = row
        let newText = dropdownModel?.selectedRowText
        observeDropdownChange?(oldText, newText ?? "")
        text = newText
    }
}
