//
//  UIView+KBShadow.m
//  keyBoard
//
//

#import "UIView+KBShadow.h"
#import <objc/runtime.h>

static const void *kKBShadowInsetsKey = &kKBShadowInsetsKey;
static const void *kKBShadowCornerRadiusKey = &kKBShadowCornerRadiusKey;

@implementation UIView (KBShadow)

- (void)kb_setCardShadowWithCornerRadius:(CGFloat)cornerRadius insets:(UIEdgeInsets)insets {
    [self kb_setShadowWithColor:[UIColor blackColor]
                        opacity:0.15f
                         radius:10.0
                         offset:CGSizeMake(0, 6)
                   cornerRadius:cornerRadius
                         insets:insets];
}

- (void)kb_setShadowWithColor:(UIColor *)color
                      opacity:(float)opacity
                       radius:(CGFloat)radius
                       offset:(CGSize)offset
                 cornerRadius:(CGFloat)cornerRadius
                       insets:(UIEdgeInsets)insets {
    CALayer *layer = self.layer;
    layer.masksToBounds = NO; // 需要让阴影显示在边界外
    layer.shadowColor = color.CGColor;
    layer.shadowOpacity = opacity;
    layer.shadowRadius = radius;
    layer.shadowOffset = offset;

    // 记录参数，供尺寸变化后更新路径
    objc_setAssociatedObject(self, kKBShadowInsetsKey, [NSValue valueWithUIEdgeInsets:insets], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, kKBShadowCornerRadiusKey, @(cornerRadius), OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    // 初次也设置一次路径（避免首次 layout 之前看不到阴影）
    [self kb_updateShadowPath];
}

- (void)kb_updateShadowPath {
    NSValue *insetsVal = objc_getAssociatedObject(self, kKBShadowInsetsKey);
    NSNumber *cornerVal = objc_getAssociatedObject(self, kKBShadowCornerRadiusKey);
    if (!insetsVal || !cornerVal) return;
    UIEdgeInsets insets = [insetsVal UIEdgeInsetsValue];
    CGFloat corner = (CGFloat)[cornerVal doubleValue];
    CGRect rect = UIEdgeInsetsInsetRect(self.bounds, insets);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:corner];
    self.layer.shadowPath = path.CGPath;
}

- (void)kb_removeShadow {
    CALayer *layer = self.layer;
    layer.shadowOpacity = 0;
    layer.shadowPath = nil;
    objc_setAssociatedObject(self, kKBShadowInsetsKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, kKBShadowCornerRadiusKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

