//
//  CBTabBarButton.swift
//  BubbleTabBar
//
//  Created by Anton Skopin on 28/11/2018.
//  Copyright © 2018 cuberto. All rights reserved.
//

import UIKit

public class CBTabBarItem: UITabBarItem {
    @IBInspectable public var tintColor: UIColor?
}

public class CBTabBarButton: UIControl {

    private var _isSelected: Bool = false
    override public var isSelected: Bool {
        get {
            return _isSelected
        }
        set {
            guard newValue != _isSelected else {
                return
            }
            if newValue {
                unfold()
            } else {
                fold()
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        configureSubviews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureSubviews()
    }
    
    init(item: UITabBarItem) {
        super.init(frame: .zero)
        tabImage = UIImageView(image: item.image)
        defer {
            self.item = item
            configureSubviews()
        }
    }
    
    public var item: UITabBarItem? {
        didSet {
            tabImage.image = item?.image?.withRenderingMode(.alwaysTemplate)
            tabLabel.text = item?.title
            if let tabItem = item as? CBTabBarItem,
               let color = tabItem.tintColor {
               tintColor = color
            }
        }
    }
    
    override public var tintColor: UIColor! {
        didSet {
            if _isSelected {
                tabImage.tintColor = tintColor
            }
            tabLabel.textColor = tintColor
            tabBg.backgroundColor = tintColor.withAlphaComponent(0.2)
        }
    }

    private var tabImage = UIImageView()
    private var tabLabel = UILabel()
    private var tabBg = UIView()
    
    private let bgHeight: CGFloat = 35.0
    private var csFoldedBgTrailing: NSLayoutConstraint!
    private var csUnfoldedBgTrailing: NSLayoutConstraint!
    private var csFoldedLblLeading: NSLayoutConstraint!
    private var csUnfoldedLblLeading: NSLayoutConstraint!
    
    private var foldedConstraints: [NSLayoutConstraint] {
        return [csFoldedLblLeading, csFoldedBgTrailing]
    }
    
    private var unfoldedConstraints: [NSLayoutConstraint] {
        return [csUnfoldedLblLeading, csUnfoldedBgTrailing]
    }
    
    
    private func configureSubviews() {
        tabImage.contentMode = .center
        tabImage.translatesAutoresizingMaskIntoConstraints = false
        tabLabel.translatesAutoresizingMaskIntoConstraints = false
        tabLabel.font = UIFont(name: "Montserrat-Regular", size: 14)
        tabLabel.adjustsFontSizeToFitWidth = true
        tabBg.translatesAutoresizingMaskIntoConstraints = false
        tabBg.isUserInteractionEnabled = false
        tabImage.setContentHuggingPriority(.required, for: .horizontal)
        tabImage.setContentHuggingPriority(.required, for: .vertical)
        tabImage.setContentCompressionResistancePriority(.required, for: .horizontal)
        tabImage.setContentCompressionResistancePriority(.required, for: .vertical)
        
        self.addSubview(tabBg)
        self.addSubview(tabLabel)
        self.addSubview(tabImage)
        
        tabBg.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        tabBg.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        tabBg.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        tabBg.heightAnchor.constraint(equalToConstant: bgHeight).isActive = true
        
        
        tabImage.leadingAnchor.constraint(equalTo: tabBg.leadingAnchor, constant: bgHeight/2.0).isActive = true
        tabImage.centerYAnchor.constraint(equalTo: tabBg.centerYAnchor).isActive = true
        tabLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        csFoldedLblLeading = tabLabel.leadingAnchor.constraint(equalTo: leadingAnchor)
        csUnfoldedLblLeading = tabLabel.leadingAnchor.constraint(equalTo: tabImage.trailingAnchor, constant: bgHeight/4.0)
        csFoldedBgTrailing = tabImage.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -bgHeight/2.0)
        csUnfoldedBgTrailing = tabLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -bgHeight/2.0)
        fold()
        setNeedsLayout()
    }
    
    private func fold(animationDuration duration: Double = 0.0) {
        /*unfoldedConstraints.forEach{ $0.isActive = false }
         foldedConstraints.forEach{ $0.isActive = true }
         UIView.animate(withDuration: duration) {
         self.tabBg.alpha = 0.0
         }
         UIView.animate(withDuration: duration * 0.4) {
         self.tabLabel.alpha = 0.0
         }
         UIView.transition(with: tabImage, duration: duration, options: [.transitionCrossDissolve], animations: {
         self.tabImage.tintColor = .black
         }, completion: nil)*/
        
        foldedConstraints.forEach{ $0.isActive = false }
        unfoldedConstraints.forEach{ $0.isActive = true }
        UIView.animate(withDuration: duration) {
            self.tabBg.alpha = 0.0
        }
        UIView.animate(withDuration: duration * 0.5, delay: duration * 0.5, options: [], animations: {
            self.tabLabel.alpha = 1.0
            self.tabLabel.textColor = #colorLiteral(red: 0.6392156863, green: 0.6392156863, blue: 0.6392156863, alpha: 1)
        }, completion: nil)
        UIView.transition(with: tabImage, duration: duration, options: [.transitionCrossDissolve], animations: {
            self.tabImage.tintColor = #colorLiteral(red: 0.6392156863, green: 0.6392156863, blue: 0.6392156863, alpha: 1)
        }, completion: nil)
        
    }
    
    private func unfold(animationDuration duration: Double = 0.0) {
        foldedConstraints.forEach{ $0.isActive = false }
        unfoldedConstraints.forEach{ $0.isActive = true }
        UIView.animate(withDuration: duration) {
            self.tabBg.alpha = 0.5
        }
        UIView.animate(withDuration: duration * 0.5, delay: duration * 0.5, options: [], animations: {
            self.tabLabel.alpha = 1.0
        }, completion: nil)
        UIView.transition(with: tabImage, duration: duration, options: [.transitionCrossDissolve], animations: {
            self.tabImage.tintColor = self.tintColor
            self.tabLabel.textColor = self.tintColor
        }, completion: nil)
    }
    
    public func setSelected(_ selected: Bool, animationDuration duration: Double = 0.0) {
        _isSelected = selected
        if selected {
            unfold(animationDuration: duration)
        } else {
            fold(animationDuration: duration)
        }
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        tabBg.layer.cornerRadius = 8.0 //tabBg.bounds.height / 2.0
    }
}
