import UIKit

class CellProgressView: UIView {

    let progressLayer = CAShapeLayer()
    
    var progress: Double = 0 {
        didSet {
            let path = UIBezierPath(rect: self.rect(for: self.progress))
            let pathFrom = self.progressLayer.path
            self.progressLayer.path = path.cgPath
            if self.progress != 0 {
                let animation = CABasicAnimation(keyPath: "path")
                animation.duration = 0.2
                animation.fromValue = pathFrom
                animation.toValue = path.cgPath
                animation.timingFunction = CAMediaTimingFunction(name: .linear)
                self.progressLayer.add(animation, forKey: "pathAnimation")
            }
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        self.progressLayer.frame = self.layer.bounds
        self.progressLayer.path = UIBezierPath(rect: self.layer.bounds).cgPath
        self.progressLayer.fillColor = UIColor.systemBlue.cgColor
        self.progressLayer.opacity = 0.3
        self.layer.addSublayer(self.progressLayer)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.progressLayer.frame = rect(for: self.progress)
    }
    
    func rect(for progress: Double) -> CGRect {
        return CGRect(x: 0, y: 0, width: self.bounds.width*CGFloat(progress), height: self.bounds.height)
    }
}
