//
//  ForecastDayCell.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 22.03.2021.
//

import UIKit

class ForecastDayCell: UITableViewCell {
    //Private
    private let dateLabel = UILabel()
    private let forecastLabel = UILabel()
    private let gradientView = GradientView(startColor: UIColor(hex: 0xffffff).withAlphaComponent(0),
                                            endColor: UIColor(hex: 0xdaddec),
                                            opacity: 0.5)
    private static var formatter:DateFormatter = {
       let fmt = DateFormatter()
        fmt.dateFormat = "d, E"
        return fmt
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        prepareCell()
        prepareGradient()
        prepareLabels()
        updateUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updateUI()
    }
    
    //Private
    private func updateUI() {
        contentView.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
        dateLabel.textColor = ThemeManager.currentTheme.primaryTextColor
        forecastLabel.textColor = ThemeManager.currentTheme.primaryTextColor
        gradientView.isHidden = interfaceStyle == .dark
    }
    
    //Public
    public func configure(today:CurrentWeather) {
        ForecastDayCell.formatter.timeZone = today.timeZone
        dateLabel.text = ForecastDayCell.formatter.string(from: today.date)
        let maxTemp = today.maxTemp?.shortString ?? "--"
        let minTemp = today.minTemp?.shortString ?? "--"
        forecastLabel.text = "\(today.type.localized(isDay: today.isDay)) | \(maxTemp)/\(minTemp)"
    }
}

//MARK:- Prepare
private extension ForecastDayCell {
    func prepareCell() {
        selectionStyle = .none
    }
    
    func prepareGradient() {
        contentView.addSubview(gradientView)
        gradientView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(41)
        }
    }
    
    func prepareLabels() {
        dateLabel.font = AppFont.SFPro.bold(size: 34)
        dateLabel.setContentHuggingPriority(.fittingSizeLevel, for: .vertical)
        contentView.addSubview(dateLabel)
        
        dateLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().inset(18)
        }
        
        forecastLabel.font = AppFont.SFPro.bold(size: 16)
        contentView.addSubview(forecastLabel)
        
        forecastLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().inset(18)
            make.top.equalTo(dateLabel.snp.bottom)
            make.bottom.equalToSuperview().inset(18)
        }
    }
    
}
