//
//  UIView+OJARectCorner.m
//  OJAKitDemo
//
//  Created by luxiaoming on 2019/3/6.
//  Copyright © 2019 luxiaoming. All rights reserved.
//

#import "UIView+OJARectCorner.h"

#define kiOS7Later SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
#define kiOS8Later SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
#define kiOS9Later SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")
#define kiOS10Later SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")
#define kiOS11Later SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0")

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

@implementation OJAMaskView

+ (Class)layerClass {
    return [CAShapeLayer class];
}

- (void)setMaskPath:(UIBezierPath *)maskPath {
    _maskPath = maskPath;
    ((CAShapeLayer *)self.layer).path = maskPath.CGPath;
}


@end

@implementation UIView (OJARectCorner)

- (void)setCornerRadius:(CGFloat)cornerRadius forRectCorner:(UIRectCorner)rectCorner {
    if (cornerRadius < 0) {
        return;
    }
    
    if (cornerRadius == 0) {
        self.maskView = nil;
        self.layer.mask = nil;
        return;
    }
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
    
    OJAMaskView *maskView = nil;
    if (path) {
        maskView =  [[OJAMaskView alloc] initWithFrame:self.bounds];
        maskView.maskPath = path;
    }
    // iOS 10 圆角毛玻璃有 bug
    
    if ([self isKindOfClass:UIVisualEffectView.class] && kiOS10Later && !kiOS11Later && rectCorner > 0) {
        self.maskView = maskView;
    } else {
        self.layer.mask = maskView.layer;
    }
}

- (void)setTopCornerRadius:(CGFloat)cornerRadius {
    [self setCornerRadius:cornerRadius forRectCorner:UIRectCornerTopLeft | UIRectCornerTopRight];
}

- (void)setBottomCornerRadius:(CGFloat)cornerRadius {
    [self setCornerRadius:cornerRadius forRectCorner:UIRectCornerBottomLeft | UIRectCornerBottomRight];
}

- (void)setAllCornerRadius:(CGFloat)cornerRadius {
    [self setCornerRadius:cornerRadius forRectCorner:UIRectCornerAllCorners];
}

- (void)setNoneCornerRadius {
    [self setCornerRadius:0 forRectCorner:UIRectCornerAllCorners];
}


@end
