//
//  TabsTableViewCell.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 9/6/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit

@objcMembers public class TabsTableViewCell: TableViewCell {
    var tabsListItemModel: TabsListItemModel? {
        return listItemModel as? TabsListItemModel
    }
    let tabs = Tabs(frame: .zero)
    var delegateObject: MVMCoreUIDelegateObject?
    var previousTabIndex = 0
    
    // MARK: - MFViewProtocol
    override public func setupView() {
        super.setupView()
        tabs.translatesAutoresizingMaskIntoConstraints = false
        tabs.delegate = self
        contentView.addSubview(tabs)
        
        NSLayoutConstraint.activate(Array(NSLayoutConstraint.pinView(toSuperview: tabs, useMargins: true).values))
        tabs.reloadData()
    }
    
    public override func updateView(_ size: CGFloat) {
        super.updateView(size)
        tabs.updateView(size)
    }
    
    // MARK: - MoleculeDelegateProtocol

    public override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        self.delegateObject = delegateObject
        if let tabsModel = tabsListItemModel?.tabs {
            tabs.set(with: tabsModel, delegateObject, additionalData)
        }
    }

    public override func reset() {
        super.reset()
        tabs.reset()
    }
    
    public override class func estimatedHeight(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?) -> CGFloat? { 46 }
}

// TODO: Move to AddRemoveMoleculeBehaviorModel
extension TabsTableViewCell: TabsDelegate {
    public func shouldSelectItem(_ indexPath: IndexPath, tabs: Tabs) -> Bool {
        guard indexPath.row != tabs.selectedIndex else { return false }
        previousTabIndex = tabs.selectedIndex
        return true
    }

    public func didSelectItem(_ indexPath: IndexPath, tabs: Tabs) {
        let index = indexPath.row
        guard let model = tabsListItemModel,
              index < model.molecules.count else { return }
        if let action = model.tabs.tabs[index].action {
            MVMCoreUIActionHandler.performActionUnstructured(with: action, sourceModel: model.tabs, additionalData: nil, delegateObject: delegateObject)
        }
        MVMCoreUIActionHandler.performActionUnstructured(with: SwapMoleculesActionModel(index < previousTabIndex ? .left : .right), sourceModel: model, additionalData: nil, delegateObject: delegateObject)
    }
}

