//
//  ELDemoButton.m
//  AILinkBleSDK_Example
//
//  Created by LarryZhang on 2023/2/4.
//  Copyright © 2023 zhengzida. All rights reserved.
//

#import "ELDemoButton.h"

@interface ELDemoButton ()

@property (nonatomic, strong) UIColor *bgColor;

@end

@implementation ELDemoButton

- (void)setCornerRadius:(CGFloat)cornerRadius {
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = cornerRadius;
}

- (void)setBorderWidth:(CGFloat)borderWidth {
    self.layer.borderWidth = borderWidth;
}

- (void)setBorderColor:(UIColor *)borderColor {
    self.layer.borderColor = borderColor.CGColor;
}

- (CGFloat)cornerRadius {
    return self.layer.cornerRadius;
}

- (CGFloat)borderWidth {
    return self.layer.borderWidth;
}

- (UIColor *)borderColor {
    return [UIColor colorWithCGColor:self.layer.borderColor];
}

- (UIColor *)mainColor {
    if (_mainColor == nil) {
        _mainColor = UIColor.blueColor;
    }
    return _mainColor;
}

- (void)setDisabled:(BOOL)disabled {
    _disabled = disabled;
    self.enabled = !disabled;
    if (disabled) {
        self.bgColor = UIColor.clearColor;
    } else {
        self.lighted = self.lighted;
    }
}

- (void)setLighted:(BOOL)lighted {
    _lighted = lighted;
    if (lighted) {
        self.bgColor = self.mainColor;
    } else {
        self.bgColor = UIColor.clearColor;
    }
}

- (void)setBgColor:(UIColor *)bgColor {
    _bgColor = bgColor;
    self.backgroundColor = bgColor;
    if (bgColor == UIColor.clearColor) {
        [self setTitleColor:self.mainColor forState:UIControlStateNormal];
    } else if ([self isDeepColor:bgColor]) {
        [self setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    } else {
        [self setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    }
}

- (BOOL)isDeepColor:(UIColor *)color {
    CIColor *ciColor = [CIColor colorWithCGColor:color.CGColor];
    CGFloat r = ciColor.red * 255;
    CGFloat g = ciColor.green * 255;
    CGFloat b = ciColor.blue * 255;
    CGFloat y = r * 0.299 + g * 0.587 + b * 0.114;
    if (y >= 192) {
        return false;
    }
    return true;
}

@end
