//
//  ShadowView.swift
//  WOKA
//
//  Created by MacBook Pro on 29/04/24.
//

import UIKit

class ShadowView: UIView {
    
    @IBInspectable var shadowColor : UIColor?
    
    @IBInspectable var cornerRadius : CGFloat = 8
    
    @IBInspectable var shadowOpacity : Float = 0.3
    
    override var bounds: CGRect {
        didSet {
            setupShadow()
        }
    }

    private func setupShadow() {
        self.layer.cornerRadius = cornerRadius
        self.layer.shadowOffset = CGSize(width: 0, height: 3)
        self.layer.shadowColor = (shadowColor != nil) ? shadowColor!.cgColor : UIColor.lightGray.cgColor
        self.layer.shadowRadius = cornerRadius
        self.layer.shadowOpacity = shadowOpacity
        self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height: 8)).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale
    }
}


extension UIView {
    func addShadowAndCorner(radius: CGFloat, shadowColor: UIColor = .black, shadowOpacity: Float = 0.5, shadowOffset: CGSize = CGSize(width: 0, height: 2), shadowRadius: CGFloat = 2) {
        layer.cornerRadius = radius
        layer.masksToBounds = false
        layer.shadowColor = shadowColor.cgColor
        layer.shadowOpacity = shadowOpacity
        layer.shadowOffset = shadowOffset
        layer.shadowRadius = shadowRadius
        
        if layer.shadowPath == nil || layer.shadowPath?.boundingBox != bounds {
            DispatchQueue.main.async {  [self] in
                layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: radius).cgPath
            }
        }
        
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
    }
}
