//
//  ForecastDetailPeriodButton.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 11.03.2021.
//

import UIKit
import SnapKit

class ForecastDetailPeriodButton: UIControl, PeriodButtonProtocol {
    private let kGraphInset:CGFloat = 10
    private let kPrecipImageWidth:CGFloat = 20
    private let dateLabel = UILabel()
    private let weatherImageView = UIImageView()
    private let weatherTypeLabel = UILabel()
    private let maxTempLabel = UILabel()
    private let minTempLabel = UILabel()
    private let precipLabel = UILabel()
    private let precipImageView = UIImageView()
    private var precipImageWidth:Constraint?
    private static var formatter: DateFormatter = {
       let fmt = DateFormatter()
        fmt.dateFormat = "d, E"
        
        return fmt
    }()
    
    //Public
    public var tinted: Bool {
        return false
    }
    public var index = -1
    var graphRect:CGRect {
        let topInset = self.maxTempLabel.frame.origin.y + self.maxTempLabel.frame.size.height + kGraphInset
        
        return .init(x: 0,
                     y: topInset,
                     width: self.bounds.width,
                     height: self.minTempLabel.frame.origin.y - topInset - kGraphInset)
    }
      
    
    required init() {
        super.init(frame: .zero)
        
        prepareButton()
        prepareDateLabel()
        prepareWeatherInfo()
        preparePreicpitaitonView()
        prepareTempLabels()
        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 = UIColor(hex: 0x1f67f3)
                self.layer.borderWidth = 0
                self.dateLabel.font = AppFont.SFPro.bold(size: 16)
                self.dateLabel.textColor = .white
                self.weatherTypeLabel.textColor = .white
                self.maxTempLabel.font = AppFont.SFPro.bold(size: 16)
                self.maxTempLabel.textColor = .white
                self.minTempLabel.textColor = .white
                self.precipLabel.textColor = .white
                self.precipImageView.tintColor = .white
            }
            else {
                self.backgroundColor = ThemeManager.currentTheme.periodButtonBackgroundColor
                self.layer.borderWidth = 1 / UIScreen.main.scale
                self.dateLabel.font = AppFont.SFPro.regular(size: 16)
                self.maxTempLabel.font = AppFont.SFPro.regular(size: 16)
                self.precipImageView.tintColor = UIColor(hex: 0x1f67f3)
                
                switch interfaceStyle {
                case .light:
                    self.dateLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
                    self.weatherTypeLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
                    self.maxTempLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
                    self.minTempLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
                    self.precipLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
                case .dark:
                    self.dateLabel.textColor = ThemeManager.currentTheme.primaryTextColor
                    self.weatherTypeLabel.textColor = ThemeManager.currentTheme.primaryTextColor
                    self.maxTempLabel.textColor = ThemeManager.currentTheme.primaryTextColor
                    self.minTempLabel.textColor = ThemeManager.currentTheme.primaryTextColor
                    self.precipLabel.textColor = ThemeManager.currentTheme.primaryTextColor
                }
            }
        }
    }
    
    func configure(dailyWeather: DailyWeather) {
        if Calendar.timeZoneCalendar(timeZone: dailyWeather.timeZone).isDateInToday(dailyWeather.date) {
            dateLabel.text = "day.today".localized()
        }
        else {
            dateLabel.text = ForecastDetailPeriodButton.formatter.string(from: dailyWeather.date)
        }
        
        weatherImageView.image = dailyWeather.type.image(isDay: true)
        weatherTypeLabel.text = dailyWeather.type.localized(isDay: true)
        maxTempLabel.text = dailyWeather.maxTemp?.settingsConverted.shortString
        minTempLabel.text = dailyWeather.minTemp?.settingsConverted.shortString
        
        let percent = dailyWeather.precipitationProbability ?? 0
        precipLabel.text = "\(percent)%"
        precipImageView.isHidden = percent == 0
        precipImageWidth?.layoutConstraints.first?.constant = percent == 0 ? 0 : kPrecipImageWidth
    }
    
    func configure(hourlyWeather: HourlyWeather) {
        assertionFailure("Not implemented for this weather type")
    }
    
    //Private
    private func updateUI() {
        self.layer.borderColor = ThemeManager.currentTheme.periodButtonBorderColor.cgColor
    }
}

private extension ForecastDetailPeriodButton {
    func prepareButton() {
        clipsToBounds = false
        layer.cornerRadius = 12
        layer.borderColor = ThemeManager.currentTheme.periodButtonBorderColor.cgColor
        layer.borderWidth = 1 / UIScreen.main.scale
    }
    
    func prepareDateLabel() {
        dateLabel.isUserInteractionEnabled = false
        dateLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
        dateLabel.font = AppFont.SFPro.regular(size: 14)
        addSubview(dateLabel)
        
        dateLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().inset(16)
            make.centerX.equalToSuperview()
        }
    }
    
    func prepareWeatherInfo() {
        weatherImageView.isUserInteractionEnabled = false
        weatherImageView.contentMode = .scaleAspectFit
        addSubview(weatherImageView)
        
        weatherImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(28)
            make.top.equalTo(dateLabel.snp.bottom).offset(8)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview().inset(20)
        }
        
        weatherTypeLabel.isUserInteractionEnabled = false
        weatherTypeLabel.textAlignment = .center
        weatherTypeLabel.numberOfLines = 2
        weatherTypeLabel.lineBreakMode = .byWordWrapping
        weatherTypeLabel.font = AppFont.SFPro.regular(size: 12)
        weatherTypeLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
        addSubview(weatherTypeLabel)
        
        weatherTypeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(weatherImageView.snp.bottom).offset(2)
            make.centerX.equalToSuperview()
            make.left.right.equalToSuperview().inset(4)
        }
    }
    
    func prepareTempLabels() {
        maxTempLabel.isUserInteractionEnabled = false
        maxTempLabel.font = AppFont.SFPro.regular(size: 16)
        maxTempLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
        addSubview(maxTempLabel)
        
        maxTempLabel.snp.makeConstraints { (make) in
            make.top.equalTo(weatherImageView.snp.bottom).offset(34)
            make.centerX.equalToSuperview()
        }
        
        minTempLabel.isUserInteractionEnabled = false
        minTempLabel.font = AppFont.SFPro.regular(size: 12)
        minTempLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
        addSubview(minTempLabel)
        
        minTempLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(precipImageView.snp.top).offset(-28)
            make.centerX.equalToSuperview()
        }
    }
    
    func preparePreicpitaitonView() {
        let container = UIView()
        
        precipImageView.isUserInteractionEnabled = false
        precipImageView.image = UIImage(named: "humidity")?.withRenderingMode(.alwaysTemplate)
        precipImageView.tintColor = UIColor(hex: 0x1f67f3)
        precipImageView.contentMode = .scaleAspectFit
        container.addSubview(precipImageView)
        
        precipImageView.snp.makeConstraints { (make) in
            self.precipImageWidth = make.width.equalTo(kPrecipImageWidth).constraint
            make.height.equalTo(12)
            make.top.left.bottom.equalToSuperview()
        }
        
        precipLabel.isUserInteractionEnabled = false
        precipLabel.textAlignment = .left
        precipLabel.font = AppFont.SFPro.regular(size: 12)
        precipLabel.textColor = ThemeManager.currentTheme.secondaryTextColor
        container.addSubview(precipLabel)
        
        precipLabel.snp.makeConstraints { (make) in
            make.left.equalTo(precipImageView.snp.right).inset(2)
            make.right.equalToSuperview()
            make.centerY.equalTo(precipImageView)
        }
        
        addSubview(container)
        container.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().inset(20)
        }
    }
}
