//
//  Tabs.swift
//  MVMCoreUI
//
//  Created by Ryan on 2/7/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import UIKit
import VDSColorTokens
import VDS

@objc public protocol TabsDelegate {
    func shouldSelectItem(_ indexPath: IndexPath, tabs: Tabs) -> Bool
    func didSelectItem(_ indexPath: IndexPath, tabs: Tabs)
}

@objcMembers open class Tabs: VDS.Tabs, VDSMoleculeViewProtocol, MVMCoreUIViewConstrainingProtocol, MFButtonProtocol {

    //--------------------------------------------------
    // MARK: - Public Properties
    //--------------------------------------------------
    open var viewModel: TabsModel!
    open var delegateObject: MVMCoreUIDelegateObject?
    open var additionalData: [AnyHashable : Any]?
        
    //delegate
    weak public var delegate: TabsDelegate? { 
        didSet {
            if let delegate {
                onTabDidSelect = { [weak self] index in
                    guard let self else { return }
                    viewModel.selectedIndex = index
                    delegate.didSelectItem(.init(row: index, section: 0), tabs: self)
                }
                
                onTabShouldSelect = { [weak self] index in
                    guard let self else { return true }
                    return delegate.shouldSelectItem(.init(row: index, section: 0), tabs: self)
                }
            }
        }
    }

    //-------------------------------------------------
    // MARK: - Layout Views
    //-------------------------------------------------
    
    open func updateView(_ size: CGFloat) {}
        
    //-------------------------------------------------
    // MARK: - Control Methods
    //-------------------------------------------------
    
    public func selectIndex(_ index: Int, animated: Bool) {
        self.selectedIndex = index
    }

    public func reloadData() { setNeedsUpdate() }
    
    //-------------------------------------------------
    // MARK: - Molecule Setup
    //-------------------------------------------------
    
    open func viewModelDidUpdate() {
        borderLine = viewModel.borderLine
        if let minWidth = viewModel.minWidth {
            self.minWidth = minWidth
        }
        orientation = viewModel.orientation
        indicatorPosition = viewModel.indicatorPosition
        overflow = viewModel.overflow
        size = viewModel.size
        selectedIndex = viewModel.selectedIndex
        surface = viewModel.style ?? .light
        fillContainer = viewModel.fillContainer
        tabModels = viewModel.tabs.compactMap { TabModel(text: $0.label.text) }
    }
}
