//
//  CircularProgressBar.swift
//  PhoneManager
//
//  Created by edy on 2025/4/3.
//

import Foundation

class CircularProgressBar: UIView {
    private var progressLayer = CAShapeLayer()
    private var trackLayer = CAShapeLayer()
    
    var textLabel : UILabel = {
        let view = UILabel()
        view.text = "Compressing..."
        view.textColor = .white
        view.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        return view
        
    }()

    var progressColor = UIColor.blue {
        didSet {
            progressLayer.strokeColor = progressColor.cgColor
        }
    }
    var trackColor = UIColor.lightGray {
        didSet {
            trackLayer.strokeColor = trackColor.cgColor
        }
    }
    var lineWidth: CGFloat = 10 {
        didSet {
            progressLayer.lineWidth = lineWidth
            trackLayer.lineWidth = lineWidth
        }
    }

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

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

    private func setup() {
        self.addSubview(self.textLabel)
        self.textLabel.snp.makeConstraints { make in
            make.width.equalTo(113 * RScreenW())
            make.height.equalTo(22)
            make.center.equalToSuperview()
        }
        
        // 创建轨道图层
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.strokeColor = trackColor.cgColor
        trackLayer.lineWidth = lineWidth
        layer.addSublayer(trackLayer)

        // 创建进度图层
        progressLayer.fillColor = UIColor.clear.cgColor
        progressLayer.strokeColor = progressColor.cgColor
        progressLayer.lineWidth = lineWidth
        progressLayer.strokeEnd = 0
        progressLayer.lineCap = .round
        layer.addSublayer(progressLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = (min(bounds.width, bounds.height) - lineWidth) / 2
        let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: -.pi / 2, endAngle: 1.5 * .pi, clockwise: true)

        trackLayer.path = circularPath.cgPath
        progressLayer.path = circularPath.cgPath
    }

    func setProgress(_ progress: CGFloat, animated: Bool = true, duration: TimeInterval = 1.0) {
        if animated {
            let animation = CABasicAnimation(keyPath: "strokeEnd")
            animation.toValue = progress
            animation.duration = duration
            animation.fillMode = .forwards
            animation.isRemovedOnCompletion = false
            progressLayer.add(animation, forKey: "progressAnimation")
        } else {
            progressLayer.strokeEnd = progress
        }
    }
}
