//
//  MenuHeaderButton.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 25.03.2021.
//

import UIKit

class MenuHeaderButton: UIControl {
    //Private
    private let imageView = UIImageView()
    private let label = UILabel()
    
    init(image:UIImage?, text:String) {
        super.init(frame: .zero)
        
        self.imageView.image = image
        self.label.text = text
        
        prepareButton()
        prepareImageView()
        prepareLabel()
        updateUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        UIView.performWithoutAnimation {
            self.alpha = 0.7
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        UIView.performWithoutAnimation {
            self.alpha = 1
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updateUI()
    }
    
    //Private
    private func updateUI() {
        backgroundColor = ThemeManager.currentTheme.containerBackgroundColor
        
        switch interfaceStyle {
        case .light:
            label.textColor = ThemeManager.currentTheme.secondaryTextColor
        case .dark:
            label.textColor = ThemeManager.currentTheme.primaryTextColor
        }
    }
}

//MARK:- Prepare
private extension MenuHeaderButton {
    func prepareButton() {
        layer.cornerRadius = 12
    }
    
    func prepareImageView() {
        imageView.isUserInteractionEnabled = false
        imageView.contentMode = .scaleAspectFit
        addSubview(imageView)
        
        imageView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().inset(24)
            make.width.height.equalTo(32)
            make.centerX.equalToSuperview()
        }
    }
    
    func prepareLabel() {
        label.isUserInteractionEnabled = false
        label.font = AppFont.SFPro.bold(size: 18)
        label.textAlignment = .center
        label.setContentHuggingPriority(.fittingSizeLevel, for: .vertical)
        addSubview(label)
        
        label.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom).offset(12).priority(.init(floatLiteral: 999))
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(24)
        }
    }
}
