//
//  UIColor+Highlight.swift
//  1Weather
//
//  Created by Dmitry Stepanets on 28.11.2020.
//

import UIKit

extension UIColor {
    private var isDarkColor: Bool {
        var r, g, b, a: CGFloat
        (r, g, b, a) = (0, 0, 0, 0)
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
        return  lum < 0.60 ? true : false
    }
    
    var highlighted:UIColor {
        return self.isDarkColor ? self.adjust(by: 30) : self.adjust(by: -30)
    }
    
    func lighten(by fraction:CGFloat) -> UIColor {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        red = lightenColor(color: red, fraction: fraction)
        green = lightenColor(color: green, fraction: fraction)
        blue = lightenColor(color: blue, fraction: fraction)
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    func darken(by fraction:CGFloat) -> UIColor {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

        getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        red = darkenColor(color: red, fraction: fraction)
        green = darkenColor(color: green, fraction: fraction)
        blue = darkenColor(color: blue, fraction: fraction)
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    private func lightenColor(color: CGFloat, fraction: CGFloat) -> CGFloat {
        return min(color + (1 - color) * fraction, 1)
    }

    private func darkenColor(color: CGFloat, fraction: CGFloat) -> CGFloat {
        return max(color - color * fraction, 0)
    }
    
    private func adjust(by percentage:CGFloat=30.0) -> UIColor {
        var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0;
        if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){
            return UIColor(red: min(r + percentage/100, 1.0),
                           green: min(g + percentage/100, 1.0),
                           blue: min(b + percentage/100, 1.0),
                           alpha: a)
        }
        else{
            return self
        }
    }
}
