//
//  TabBarViewController.swift
//  
//
//  Created by Liz Cross on 2018-11-21.
//

import Foundation

class TabBarViewController: UIViewController {
    let tabBar = UITabBar()
    private let tabBarContainer = UIView()

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tabBar.invalidateIntrinsicContentSize()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Very similar implementation to HeaderBarPlugin
        // TabBar and TabBarContainer extend all the way to the bottom of the screen
        // while viewController.view only extends to the bottom safe area
        // This allows the TabBarPlugin to be placed inside a bottom view on an anchored layout
        // that is constrained within the safe area while still having the bottom of the tab bar
        // extend to the bottom of the screen (ie. bottom of the screen is outside of the safe area)

        tabBar.isTranslucent = true
        tabBar.translatesAutoresizingMaskIntoConstraints = false

        tabBarContainer.addSubview(tabBar)
        tabBarContainer.sizeToFit()
        tabBarContainer.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tabBarContainer)

        tabBar.pinToSuperviewEdgesHorizontally()
        var bottomPadding: CGFloat

        if #available(iOS 11.0, *) {
            let window = UIApplication.shared.keyWindow
            bottomPadding = window?.safeAreaInsets.bottom ?? 0.0
            self.additionalSafeAreaInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: bottomPadding, right: 0.0)
        } else {
            bottomPadding = 0.0

        }

        tabBar.pinToSuperviewEdgesVertically()

        let tabBarContainerConstraints = [
            NSLayoutConstraint(item: tabBarContainer,
                               attribute: .top,
                               relatedBy: .equal,
                               toItem: tabBarContainer.superview,
                               attribute: .top,
                               multiplier: 1,
                               constant: 0.0),
            NSLayoutConstraint(item: tabBarContainer,
                               attribute: .bottom,
                               relatedBy: .equal,
                               toItem: tabBarContainer.superview,
                               attribute: .bottom,
                               multiplier: 1,
                               constant: bottomPadding)
        ]
        tabBarContainer.superview?.addConstraints(tabBarContainerConstraints)
        tabBarContainer.pinToSuperviewEdgesHorizontally()

    }
}
