//
//  ForecastPeriodButton.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 15.02.2021.
//

import UIKit

class ForecastPeriodButton: UIControl, PeriodButtonProtocol {
    //Private
    private static var hourlyFormatter: DateFormatter = {
        let fmt = DateFormatter()
        fmt.dateFormat = "h a"
        return fmt
    }()
    private static var dailyFormatter: DateFormatter = {
        let fmt = DateFormatter()
        fmt.dateFormat = "d, E"
        return fmt
    }()
    private let kGraphInset:CGFloat = 10
    private let forecastImageView = UIImageView()
    private let tempLabel = UILabel()
    private let indicatorImageView = UIImageView()
    private let minTempLabel = UILabel()
    private let timeLabel = UILabel()
  
    //Public
    public var tinted: Bool {
        return true
    }
    public var index = -1
    var graphRect:CGRect {
        let topInset = self.tempLabel.frame.origin.y + self.tempLabel.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()
        prepareForecastImage()
        prepareTempLabel()
        prepareTimeLabel()
        preparePeriodIndicator()
        prepareMinTempLabel()
        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.tempLabel.font = AppFont.SFPro.bold(size: 16)
                self.minTempLabel.font = AppFont.SFPro.bold(size: 12)
                self.timeLabel.font = AppFont.SFPro.bold(size: 12)
                self.indicatorImageView.alpha = 1.0
                self.layer.shadowOpacity = 0.65
                self.layer.borderWidth = 1 / UIScreen.main.scale
            }
            else {
                self.backgroundColor = ThemeManager.currentTheme.periodButtonBackgroundColor
                self.tempLabel.font = AppFont.SFPro.regular(size: 16)
                self.minTempLabel.font = AppFont.SFPro.regular(size: 12)
                self.timeLabel.font = AppFont.SFPro.regular(size: 12)
                self.indicatorImageView.alpha = 0.5
                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:
            tempLabel.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:
            tempLabel.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) {
        self.tempLabel.text = dailyWeather.maxTemp?.settingsConverted.shortString
        self.minTempLabel.text = dailyWeather.minTemp?.settingsConverted.shortString
        self.indicatorImageView.image = nil
        self.forecastImageView.image = dailyWeather.type.image(isDay: true)
        if Calendar.timeZoneCalendar(timeZone: dailyWeather.timeZone).isDateInToday(dailyWeather.date) {
            self.timeLabel.text = "day.today".localized()
        }
        else {
            ForecastPeriodButton.dailyFormatter.timeZone = dailyWeather.timeZone
            self.timeLabel.text = ForecastPeriodButton.dailyFormatter.string(from: dailyWeather.date)
        }
    }
    
    func configure(hourlyWeather: HourlyWeather) {
        self.tempLabel.text = hourlyWeather.temp?.settingsConverted.shortString
        self.minTempLabel.text = nil
        self.indicatorImageView.image = nil
        if Calendar.isNow(fromDate: hourlyWeather.date, timeZone: hourlyWeather.timeZone) {
            self.timeLabel.text = "day.now".localized().uppercased()
        }
        else {
            ForecastPeriodButton.hourlyFormatter.timeZone = hourlyWeather.timeZone
            self.timeLabel.text = ForecastPeriodButton.hourlyFormatter.string(from: hourlyWeather.date)
        }
    }
}

private extension ForecastPeriodButton {
    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
        }
    }
    
    func prepareForecastImage() {
        forecastImageView.isUserInteractionEnabled = false
        forecastImageView.contentMode = .scaleAspectFit
        forecastImageView.image = UIImage(named: "partly_cloudy")
        addSubview(forecastImageView)
        
        forecastImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(28)
            make.top.left.right.equalToSuperview().inset(20)
            make.centerX.equalToSuperview()
        }
    }
    
    func prepareTempLabel() {
        timeLabel.isUserInteractionEnabled = false
        tempLabel.font = AppFont.SFPro.regular(size: 16)
        addSubview(tempLabel)
        
        tempLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(forecastImageView.snp.bottom).offset(17)
        }
    }
    
    func prepareMinTempLabel() {
        minTempLabel.isUserInteractionEnabled = false
        minTempLabel.font = AppFont.SFPro.regular(size: 12)
        addSubview(minTempLabel)
        
        minTempLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(indicatorImageView.snp.top).offset(-10)
        }
    }
    
    func preparePeriodIndicator() {
        indicatorImageView.isUserInteractionEnabled = false
        indicatorImageView.contentMode = .scaleAspectFit
        indicatorImageView.image = UIImage(named: "hot_indicator")
        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)
        }
    }
}
