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

import UIKit

private extension UIImage{
    
    //creates a UIImage given a UIColor
    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }
}

class ForecastTimePeriodControl: UISegmentedControl {
    private let segmentInset: CGFloat = 2       //your inset amount
    private let segmentImage: UIImage? = UIImage(color: UIColor.gray)    //your color
    
    override func layoutSubviews(){
        super.layoutSubviews()
        
        //background
        layer.cornerRadius = 12
        
        //foreground
        let foregroundIndex = numberOfSegments
        if subviews.indices.contains(foregroundIndex),
           let foregroundImageView = subviews[foregroundIndex] as? UIImageView
        {
            foregroundImageView.bounds = foregroundImageView.bounds.insetBy(dx: segmentInset, dy: segmentInset)
            foregroundImageView.image = segmentImage    //substitute with our own colored image
            foregroundImageView.layer.removeAnimation(forKey: "SelectionBounds")    //this removes the weird scaling animation!
            foregroundImageView.layer.masksToBounds = true
            foregroundImageView.layer.cornerRadius = 9
        }
    }
    
    private func updateSegment(segmentImageView: UIImageView) {
        
    }
}

private extension ForecastTimePeriodControl {
    
}
