//
//  ScannerView.swift
//  DWP
//
//  Created by Ahmed Wahdan on 17/12/2024.
//

import UIKit

class ScannerView: UIView {
    
    private let scanLine = UIView()
    private let gradientLayer = CAGradientLayer()
    private let scanLineHeight: CGFloat = 15.0
    private let animationDuration: TimeInterval = 1.5
    private let gradientColor = #colorLiteral(red: 0.3607843137, green: 0.8235294118, blue: 1, alpha: 1) // Blue Color
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupScannerView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupScannerView()
    }
    
    private func setupScannerView() {
        layer.cornerRadius = 16.0
        layer.borderWidth = 4.0
        layer.borderColor = gradientColor.cgColor
        clipsToBounds = true
        // Gradient Layer Setup
        gradientLayer.colors = [
            gradientColor.withAlphaComponent(0.0).cgColor,
            gradientColor.withAlphaComponent(0.1).cgColor,
            gradientColor.withAlphaComponent(0.2).cgColor,
            gradientColor.withAlphaComponent(0.3).cgColor,
            gradientColor.withAlphaComponent(0.4).cgColor,
            gradientColor.withAlphaComponent(0.8).cgColor,
            gradientColor.withAlphaComponent(0.8).cgColor,
            gradientColor.withAlphaComponent(0.4).cgColor,
            gradientColor.withAlphaComponent(0.3).cgColor,
            gradientColor.withAlphaComponent(0.2).cgColor,
            gradientColor.withAlphaComponent(0.1).cgColor,
            gradientColor.withAlphaComponent(0.0).cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 0, y: 1)
        gradientLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: scanLineHeight)
        
        // Scan Line with Gradient
        scanLine.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: scanLineHeight)
        scanLine.layer.addSublayer(gradientLayer)
        self.addSubview(scanLine)
    }
    
    func startScanAnimation() {
        // Reset line position to the top
        scanLine.frame.origin.y = -scanLineHeight
        
        // Move line down and back up
        let positionAnimation = CABasicAnimation(keyPath: "position.y")
        positionAnimation.fromValue = -scanLineHeight / 2
        positionAnimation.toValue = self.bounds.height + scanLineHeight / 2
        positionAnimation.duration = animationDuration
        positionAnimation.repeatCount = .infinity
        positionAnimation.autoreverses = true
        positionAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        
        // Add animation to scan line
        scanLine.layer.add(positionAnimation, forKey: "verticalScan")
    }
    
    func stopScanAnimation() {
        scanLine.layer.removeAllAnimations()
    }
}
