//
//  ForecastWindButton.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 23.03.2021.
//

import UIKit

class ForecastWindButton: UIControl, PeriodButtonProtocol {
    //Private
    private static var hourlyFormatter: DateFormatter = {
        let fmt = DateFormatter()
        fmt.dateFormat = "h a"
        return fmt
    }()
    private let kGraphInset:CGFloat = 10
    private let windInfoLabel = UILabel()
    private let directionImageView = UIImageView()
    private let indicatorImageView = UIImageView()
    private let timeLabel = UILabel()
    
    //Public
    var index: Int = -1
    var tinted: Bool {
        return true
    }
    var graphRect: CGRect {
        let topInset = self.directionImageView.frame.origin.y + self.directionImageView.frame.size.height + kGraphInset
        
        return .init(x: 0,
                     y: topInset,
                     width: self.bounds.width,
                     height: self.indicatorImageView.frame.origin.y - topInset - kGraphInset)
    }
    
    required init() {
        super.init(frame: .zero)
        
        prepareButton()
        prepareInfoLabel()
        prepareDirectionImageView()
        prepareTimeLabel()
        prepareWindIndicator()
        updateUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updateUI()
    }
    
    override var isSelected: Bool {
        didSet {
            if isSelected {
                self.backgroundColor = ThemeManager.currentTheme.periodButtonSelectedBackgroundColor
                self.windInfoLabel.font = AppFont.SFPro.bold(size: 16)
                self.timeLabel.font = AppFont.SFPro.bold(size: 12)
                self.layer.shadowOpacity = 0.65
                self.layer.borderWidth = 1 / UIScreen.main.scale
            }
            else {
                self.backgroundColor = ThemeManager.currentTheme.periodButtonBackgroundColor
                self.windInfoLabel.font = AppFont.SFPro.regular(size: 16)
                self.timeLabel.font = AppFont.SFPro.regular(size: 12)
                self.layer.shadowOpacity = 0
                self.layer.borderWidth = 0
            }
        }
    }
    
    //Private
    private func updateUI() {
        self.layer.borderColor = ThemeManager.currentTheme.periodButtonBorderColor.cgColor
        self.layer.shadowColor = ThemeManager.currentTheme.periodButtonShadowColor.cgColor
        self.backgroundColor = ThemeManager.currentTheme.periodButtonBackgroundColor
        
        switch interfaceStyle {
        case .light:
            windInfoLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
            timeLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
            
            self.layer.shadowOffset = .init(width: 5, height: 5)
            self.layer.shadowRadius = 18
            self.layer.shadowOpacity = 0.65
        case .dark:
            windInfoLabel.textColor = UIColor.white
            timeLabel.textColor = UIColor.white
            
            self.layer.shadowOffset = .init(width: 6, height: 6)
            self.layer.shadowRadius = 6
            self.layer.shadowOpacity = 0.65
        }
    }
    
    //Public
    func configure(dailyWeather: DailyWeather) {
        assertionFailure("Not implemented")
    }
    
    func configure(hourlyWeather: HourlyWeather) {
        let direction = hourlyWeather.windDirection?.rawValue ?? "--"
        let speed = hourlyWeather.windSpeed?.string ?? "--"
        windInfoLabel.text = "\(direction.uppercased())\n\(speed.uppercased())"
        let degrees = hourlyWeather.windDirection?.degrees ?? 0
        directionImageView.transform = CGAffineTransform(rotationAngle: degrees * .pi / 180)
        
        if Calendar.isNow(fromDate: hourlyWeather.date, timeZone: hourlyWeather.timeZone) {
            timeLabel.text = "day.now".localized().uppercased()
        }
        else {
            ForecastWindButton.hourlyFormatter.timeZone = hourlyWeather.timeZone
            timeLabel.text = ForecastWindButton.hourlyFormatter.string(from: hourlyWeather.date)
        }
    }
}

//MARK:- Prepare
private extension ForecastWindButton {
    func prepareButton() {
        clipsToBounds = false
        backgroundColor = UIColor.white
        layer.cornerRadius = 12
        layer.borderColor = ThemeManager.currentTheme.periodButtonBorderColor.cgColor
        layer.borderWidth = 1 / UIScreen.main.scale
        layer.shadowColor = ThemeManager.currentTheme.periodButtonShadowColor.cgColor
        
        if interfaceStyle == .light {
            self.layer.shadowOffset = .init(width: 5, height: 5)
            self.layer.shadowRadius = 18
            self.layer.shadowOpacity = 0.65
        }
        else {
            self.layer.shadowOffset = .init(width: 6, height: 6)
            self.layer.shadowRadius = 6
            self.layer.shadowOpacity = 0.65
        }
        
        self.snp.makeConstraints { (make) in
            make.width.equalTo(70)
        }
    }
    
    func prepareInfoLabel() {
        windInfoLabel.isUserInteractionEnabled = false
        windInfoLabel.font = AppFont.SFPro.regular(size: 16)
        windInfoLabel.textAlignment = .center
        windInfoLabel.numberOfLines = 2
        windInfoLabel.lineBreakMode = .byWordWrapping
        addSubview(windInfoLabel)
        
        windInfoLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().inset(16)
            make.left.right.equalToSuperview().inset(2)
        }
    }
    
    func prepareDirectionImageView() {
        directionImageView.contentMode = .scaleAspectFit
        directionImageView.image = UIImage(named: "wind_direction")
        directionImageView.tintColor = UIColor(hex: 0x8fc2ff)
        addSubview(directionImageView)
        
        directionImageView.snp.makeConstraints { (make) in
            make.top.equalTo(windInfoLabel.snp.bottom).offset(36)
            make.width.height.equalTo(18)
            make.centerX.equalToSuperview()
        }
    }
    
    func prepareWindIndicator() {
        indicatorImageView.isUserInteractionEnabled = false
        indicatorImageView.isHidden = true
        indicatorImageView.contentMode = .scaleAspectFit
        indicatorImageView.image = UIImage(named: "blowingDust")
        addSubview(indicatorImageView)
        
        indicatorImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(12)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(timeLabel.snp.top).offset(-15)
        }
    }
    
    func prepareTimeLabel() {
        timeLabel.isUserInteractionEnabled = false
        timeLabel.font = AppFont.SFPro.regular(size: 12)
        timeLabel.text = "9 AM"
        addSubview(timeLabel)
        
        timeLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().inset(20)
        }
    }
}
