//
//  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.paddingBeforeFirstTab = false
        tabs.translatesAutoresizingMaskIntoConstraints = false
        tabs.delegate = self
        tabs.bottomLine.setStyle(.none)
        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 }
        if let model = tabsListItemModel {
            MVMCoreActionHandler.shared()?.asyncHandleAction(with: RemoveMoleculesActionModel(indexPath.row < tabs.selectedIndex ? .right : .left), additionalData: [KeySourceModel: model], delegateObject: delegateObject)
        }
        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 {
            MVMCoreActionHandler.shared()?.asyncHandleAction(with: action, additionalData: [KeySourceModel: model.tabs], delegateObject:delegateObject)
        }
        MVMCoreActionHandler.shared()?.asyncHandleAction(with: AddMoleculesActionModel(index < previousTabIndex ? .left : .right), additionalData: [KeySourceModel: model], delegateObject: delegateObject)
    }
}

