//
//  YHBaseCornerRadiusBorderView.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHBaseCornerRadiusBorderView: UIView {

    private var radius: CGFloat = 2
    private var corner: UIRectCorner = .allCorners
    var lineWidth: CGFloat? {
        didSet {
            if lineWidth != oldValue {
                boarderLayers?.forEach {
                    $0.removeFromSuperlayer()
                }
                boarderLayers = nil
                boarderLayers = createRoundedCornersAndBorder(corners: corner, radii: CGSize(width: radius, height: radius), lineWidth: lineWidth, lineColor: lineColor)
            }
        }
    }
    var lineColor: CGColor? {
        didSet {
            if lineColor != oldValue {
                boarderLayers?.forEach {
                    $0.removeFromSuperlayer()
                }
                boarderLayers = nil
                boarderLayers = createRoundedCornersAndBorder(corners: corner, radii: CGSize(width: radius, height: radius), lineWidth: lineWidth, lineColor: lineColor)
            }
        }
    }
    
    public init(cornerRadius: CGFloat, corner: UIRectCorner, lineWidth: CGFloat?, lineColor: CGColor?) {
        self.corner = corner
        self.radius = cornerRadius
        self.lineWidth = lineWidth
        self.lineColor = lineColor
        super.init(frame: CGRect.zero)
    }
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var boarderLayers: [CAShapeLayer]?
    
    private var viewBounds = CGRect.zero {
        didSet {
            boarderLayers?.forEach {
                $0.removeFromSuperlayer()
            }
            boarderLayers = nil
            boarderLayers = createRoundedCornersAndBorder(corners: corner, radii: CGSize(width: radius, height: radius), lineWidth: lineWidth, lineColor: lineColor)
        }
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        viewBounds = bounds
    }

}
