//
//  TabBarViewController.swift
//  App
//
//  Created by James Magahern on 10/28/20.
//

import Combine
import UIKit

class TabBarViewController: UIViewController, TabBarViewDataSource, TabBarViewDelegate
{
    let tabBarView = TabBarView()
    
    private var tabController: TabController
    
    private var tabObserver: AnyCancellable?
    private var activeTabIndexObserver: AnyCancellable?
    
    override func loadView() {
        self.view = tabBarView
    }
    
    init(tabController: TabController) {
        self.tabController = tabController
        super.init(nibName: nil, bundle: nil)
        
        tabBarView.dataSource = self
        tabBarView.delegate = self
        tabBarView.reloadTabs()
        
        tabObserver = tabController.$tabs.sink(receiveValue: { [unowned self] (newTabs: [Tab]) in
            DispatchQueue.main.async { self.tabBarView.reloadTabs() }
        })
        
        activeTabIndexObserver = tabController.$activeTabIndex.sink(receiveValue: { [unowned self] (activeIndex: Int) in
            tabBarView.activateTab(atIndex: activeIndex)
        })
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: TabBarViewDelegate
    func tabBarView(_ tabBarView: TabBarView, didClickToActivateTabAtIndex index: Int) {
        tabController.activeTabIndex = index
    }
    
    func tabBarView(_ tabBarView: TabBarView, didClickToCloseTabAtIndex index: Int) {
        let tab = tabController.tabs[index]
        tabController.closeTab(tab)
    }
    
    // MARK: TabBarViewDataSource
    func numberOfTabs(forTabBarView: TabBarView) -> Int {
        return tabController.tabs.count
    }
    
    func tabBarView(_ tabBarView: TabBarView, titleForTabAtIndex index: Int) -> String {
        let defaultTitle = "New Tab"
        
        if let title = tabController.tabs[index].title, title.count > 0 {
            return title
        }
        
        return defaultTitle
    }
    
    func tabBarView(_ tabBarView: TabBarView, imageForTabAtIndex index: Int) -> UIImage? {
        tabController.tabs[index].favicon
    }
    
    func tabBarView(_ tabBarView: TabBarView, uniqueIdentifierForTabAtIndex index: Int) -> UUID {
        tabController.tabs[index].identifier
    }
    
}
