//
//  ShimmerEffectView.swift
//  WOKA
//
//  Created by MacBook Pro on 20/06/24.
//

import UIKit

class ShimmerEffectView: UIView {

//    var gradientColorOne: CGColor = UIColor(red: 0.176, green: 0.012, blue: 0.561, alpha: 1.0).cgColor
    var gradientColorOne: CGColor = #colorLiteral(red: 0.2364082336, green: 0.1172600761, blue: 0.6259267926, alpha: 1).cgColor
//    var gradientColorTwo: CGColor = UIColor(white: 0.925, alpha: 1.0).cgColor
    var gradientColorTwo: CGColor = #colorLiteral(red: 0.9254901961, green: 0.9254901961, blue: 0.9254901961, alpha: 1).cgColor

    
    private var gradientLayer: CAGradientLayer?

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {
        self.clipsToBounds = true
    }

    private func addGradientLayer() -> CAGradientLayer {
        let gradientLayer = CAGradientLayer()
        
        gradientLayer.frame = self.bounds
        
        // Calculate points for a 70-degree angle (slant)
        let angleInRadians = CGFloat(70) * .pi / 180.0 // Convert degrees to radians
        
        let startPointX = sin(angleInRadians)
        let startPoint = CGPoint(x: -startPointX, y: 1.0)
        
        let endPointX = cos(angleInRadians)
        let endPoint = CGPoint(x: 1.0 + endPointX, y: 1.0)
        
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.colors = [gradientColorOne, gradientColorTwo, gradientColorOne]
        gradientLayer.locations = [0.0, 0.5, 1.0]
        self.layer.addSublayer(gradientLayer)
        
        return gradientLayer
    }

    private func addAnimation() -> CABasicAnimation {
        let animation = CABasicAnimation(keyPath: "locations")
        
        // Adjust fromValue and toValue for a 70-degree angle (slant)
        animation.fromValue = [-1.0, -0.5, 0.0]
        animation.toValue = [1.0, 1.5, 2.0]

        animation.repeatCount = .infinity
        animation.duration = 1.2
        return animation
    }

    func startShimmer() {
        let gradientLayer = addGradientLayer()
        let animation = addAnimation()

        gradientLayer.add(animation, forKey: animation.keyPath)
        self.gradientLayer = gradientLayer
    }

    func stopShimmer() {
        guard let gradientLayer = self.gradientLayer else { return }

        gradientLayer.removeAllAnimations()
        gradientLayer.removeFromSuperlayer()
        self.gradientLayer = nil
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer?.frame = self.bounds
    }
}
