//
//  TabBar.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 5/28/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//


@objcMembers open class TabBar: UITabBar, MoleculeViewProtocol, TabBarProtocol, UITabBarDelegate {
    
    public var model: TabBarModel
    public var delegateObject: MVMCoreUIDelegateObject?
    public let line = Line()

    required public init(model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        guard let model = model as? TabBarModel else { fatalError("model is not TabBarModel") }
        self.model = model
        super.init(frame: .zero)
        
        delegate = self
        translatesAutoresizingMaskIntoConstraints = false
        line.addLine(to: self, edge: .top, useMargin: false)
        line.backgroundColor = .mvmCoolGray3
        set(with: model, delegateObject, additionalData)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        guard let model = model as? TabBarModel else { return }
        self.model = model
        
        // Set appearance
        if #available(iOS 13.0, *) {
            let appearance = UITabBarAppearance()
            appearance.backgroundColor = model.backgroundColor?.uiColor
            set(tabItemAppearance: appearance.stackedLayoutAppearance, model: model)
            set(tabItemAppearance: appearance.inlineLayoutAppearance, model: model)
            set(tabItemAppearance: appearance.compactInlineLayoutAppearance, model: model)
            standardAppearance = appearance
        } else {
            // Fallback on earlier versions
            backgroundColor = model.backgroundColor?.uiColor
            tintColor = model.selectedColor.uiColor
            unselectedItemTintColor = model.unSelectedColor.uiColor
            barTintColor = model.backgroundColor?.uiColor
            isTranslucent = false
        }
        
        // Add buttons
        var tabs: [UITabBarItem] = []
        for (index, tab) in model.tabs.enumerated() {
            let tabBarItem = UITabBarItem(title: tab.title, image: MVMCoreCache.shared()?.getImageFromRegisteredBundles(tab.image), tag: index)
            tabBarItem.accessibilityLabel = tab.accessibilityText
            if #available(iOS 13.0, *) {
            } else {
                tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3)
                tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: MFFonts.mfFontTXRegular(8)], for: .normal)
            }
            tabs.append(tabBarItem)
        }
        setItems(tabs, animated: false)
        selectedItem = tabs[model.selectedTab]
    }
    
    /// Sets the item colors.
    @available(iOS 13.0, *)
    private func set(tabItemAppearance: UITabBarItemAppearance, model: TabBarModel) {
        tabItemAppearance.normal.iconColor = model.unSelectedColor.uiColor
        tabItemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: model.unSelectedColor.uiColor, NSAttributedString.Key.font: MFFonts.mfFontTXRegular(8)]
        tabItemAppearance.normal.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3)

        tabItemAppearance.selected.iconColor = model.selectedColor.uiColor
        tabItemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: model.selectedColor.uiColor, NSAttributedString.Key.font: MFFonts.mfFontTXRegular(8)]
        tabItemAppearance.selected.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3)
    }
    
    // MARK: - UITabBarDelegate
    public func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        model.selectedTab = item.tag
        Button.performButtonAction(with: model.tabs[item.tag].action, button: item, delegateObject: delegateObject, additionalData: nil)
    }
    
    // MARK: - TabBarProtocol
    public func highlightTab(at index: Int) {
        MVMCoreDispatchUtility.performBlock(onMainThread: {
            guard let newSelectedItem = self.items?[index] else { return }
            self.model.selectedTab = index
            self.selectedItem = newSelectedItem
        })
    }
    
    public func selectTab(at index: Int) {
        MVMCoreDispatchUtility.performBlock(onMainThread: {
            guard let newSelectedItem = self.items?[index] else { return }
            self.selectedItem = newSelectedItem
            self.tabBar(self, didSelect: newSelectedItem)
        })
    }
    
    public func currentTabIndex() -> Int { model.selectedTab }
}

extension UITabBarItem: MFButtonProtocol { }
