//
//  UIButton+DDCategory.m
//  DDCategoryKit_Private
//  Created by DDIsFriend on 2022/7/29.

#import "UIButton+DDCategory.h"
#import <DDCategoryKit_Private/NSObject+DDCategory.h>

DDCustomButtonAttributedStringKey const DDCustomButtonAttributedStringState = @"DDCustomButtonAttributedStringStateName";
DDCustomButtonAttributedStringKey const DDCustomButtonAttributedStringAttributedText = @"DDCustomButtonAttributedStringTextName";
DDCustomButtonAttributedStringKey const DDCustomButtonAttributedStringImage = @"DDCustomButtonAttributedStringImage";

@implementation UIButton (DDCategory)
+ (void)load{

    static dispatch_once_t onceToken;
    __weak typeof(self) weakSelf = self;
    dispatch_once(&onceToken, ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        [strongSelf dd_originSelector:@selector(pointInside:withEvent:) swizzleSelector:@selector(dd_pointInside:withEvent:)];
        [strongSelf dd_originSelector:@selector(layoutSubviews) swizzleSelector:@selector(dd_layoutSubviews)];

    });
    
}
+ (instancetype)dd_initCustomButton{
    return [UIButton buttonWithType:UIButtonTypeCustom];
}

- (instancetype)dd_addTarget:(nullable id)target action:(nonnull SEL)action forControlEvents:(UIControlEvents)controlEvents {
    [self addTarget:target action:action forControlEvents:controlEvents];
    return self;
}

- (void)dd_layoutSubviews{
    [self dd_layoutSubviews];
    
}

/**
 * if another button is added to the view beside the button added before, it is too close less the widthDelta, the valid touch area is belong to the button added later.
 */
- (BOOL)dd_pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
//    if (UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero)) {
//        return [self dd_pointInside:point withEvent:event];
//    }
    
    CGRect bounds = self.bounds;

    CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);

    CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
  
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);

    return CGRectContainsPoint(bounds, point);
}
@end

@implementation UIButton (AttributedString)

+ (instancetype)dd_initWithAttributedTitles:(NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)attributedTitles
{
    return [self dd_initWithAttributedTitles:attributedTitles images:nil backgroundColor:nil];
}

+ (instancetype)dd_initWithImages:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)images
{
    return [self dd_initWithAttributedTitles:nil images:images backgroundColor:nil];
}

+ (instancetype)dd_initWithBackgroundColor:(UIColor *)backgroundColor{
    return [self dd_initWithAttributedTitles:nil images:nil backgroundColor:backgroundColor];
}

+ (instancetype)dd_initWithAttributedTitles:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)attributedTitles images:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)images backgroundColor:(nullable UIColor *)backgroundColor {
    return [UIButton dd_initWithType:UIButtonTypeCustom attributedTitles:attributedTitles images:images backgroundColor:backgroundColor];
}

+ (instancetype)dd_initWithType:(UIButtonType)buttonType attributedTitles:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)attributedTitles images:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)images backgroundColor:(nullable UIColor *)backgroundColor {
    return [[UIButton buttonWithType:buttonType] dd_setAttributedTitles:attributedTitles images:images backgroundColor:backgroundColor];
}

- (instancetype)dd_setAttributedTitles:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)attributedTitles images:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)images backgroundColor:(nullable UIColor *)backgroundColor {
//    if (@available(iOS 15.0, *)) {
//        UIButtonConfiguration *configuration = self.configuration;
//        if (configuration == nil){
//            configuration = [UIButtonConfiguration plainButtonConfiguration];
//            self.configuration = configuration;
//        }
//
//        configuration.baseBackgroundColor = backgroundColor;
//        self.configuration = configuration;
//        self.backgroundColor = backgroundColor;
//
//        __weak typeof(self) weakSelf = self;
//        self.configurationUpdateHandler = ^(UIButton *button){
//            __strong typeof(weakSelf) strongSelf = weakSelf;
//
//            NSAttributedString *textAttributes = nil;
//            UIImage *image = nil;
//            for (NSDictionary *dict in attributedTitles) {
//                if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }
//            }
//
//            for (NSDictionary *dict in images){
//                if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }
//            }
//
//            configuration.attributedTitle = textAttributes;
//            configuration.image = image;
//            strongSelf.configuration = configuration;
//        };
//
//    }else{
//        self.adjustsImageWhenHighlighted = false;
//        [self setBackgroundColor:backgroundColor];
//        for (NSDictionary *dict in attributedTitles) {
//            if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateNormal];
//            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateSelected];
//            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateHighlighted];
//            }
//
//        }
//        for (NSDictionary *dict in images){
//            if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateNormal];
//                }
//            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateSelected];
//                }
//            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateHighlighted];
//                }
//            }
//        }
//    }
    return [[[self dd_setAttributedTitles:attributedTitles] dd_setImages:images] dd_setBackgroundColor:backgroundColor];
}

- (instancetype)dd_setAttributedTitles:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)attributedTitles{
//    if (@available(iOS 15.0, *)) {
//        UIButtonConfiguration *configuration = self.configuration;
//        if (configuration == nil){
//            configuration = [UIButtonConfiguration plainButtonConfiguration];
//            self.configuration = configuration;
//        }
//
//        __weak typeof(self) weakSelf = self;
//        self.configurationUpdateHandler = ^(UIButton *button){
//            __strong typeof(weakSelf) strongSelf = weakSelf;
//
//            NSAttributedString *textAttributes = nil;
//            for (NSDictionary *dict in attributedTitles) {
//                if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                    textAttributes = dict[DDCustomButtonAttributedStringAttributedText];
//                }
//            }
//            configuration.attributedTitle = textAttributes;
//            strongSelf.configuration = configuration;
//        };
//
//    }else{
        self.adjustsImageWhenHighlighted = false;

        for (NSDictionary *dict in attributedTitles) {
            if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateNormal];
            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateSelected];
            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
                [self setAttributedTitle:dict[DDCustomButtonAttributedStringAttributedText] forState:UIControlStateHighlighted];
            }

        }
//    }
    return self;
}

- (instancetype)dd_setImages:(nullable NSArray<NSDictionary<DDCustomButtonAttributedStringKey,id> *> *)images{
//    if (@available(iOS 15.0, *)) {
//        UIButtonConfiguration *configuration = self.configuration;
//        if (configuration == nil){
//            configuration = [UIButtonConfiguration plainButtonConfiguration];
//            self.configuration = configuration;
//        }
//
//        __weak typeof(self) weakSelf = self;
//        self.configurationUpdateHandler = ^(UIButton *button){
//            __strong typeof(weakSelf) strongSelf = weakSelf;
//
//            UIImage *image = nil;
//            for (NSDictionary *dict in images){
//                if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
//                    if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
//                        image = dict[DDCustomButtonAttributedStringImage];
//                    }
//                }
//            }
//            configuration.image = image;
//            strongSelf.configuration = configuration;
//        };
//
//    }else{
        self.adjustsImageWhenHighlighted = false;

        for (NSDictionary *dict in images){
            if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateNormal)]) {
                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateNormal];
                }
            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateSelected)]){
                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateSelected];
                }
            }else if ([dict[DDCustomButtonAttributedStringState] isEqualToNumber:@(DDCustomButtonStateHighlight)]){
                if(![dict[DDCustomButtonAttributedStringImage] isKindOfClass:[NSNull class]]){
                    [self setImage:dict[DDCustomButtonAttributedStringImage] forState:UIControlStateHighlighted];
                }
            }
        }
//    }
    return self;
}

- (instancetype)dd_setBackgroundColor:(nullable UIColor *)backgroundColor{
//    if (@available(iOS 15.0, *)) {
//        UIButtonConfiguration *configuration = self.configuration;
//        if (configuration == nil){
//            configuration = [UIButtonConfiguration plainButtonConfiguration];
//            self.configuration = configuration;
//        }
//        configuration.baseBackgroundColor = backgroundColor;
//        self.configuration = configuration;
//        self.backgroundColor = backgroundColor;
//
//    }else{
        self.adjustsImageWhenHighlighted = false;
        [self setBackgroundColor:backgroundColor];
//    }
    return self;
}

@end

@implementation UIButton (Placement)
- (instancetype)dd_customizeWithStyle:(DDCustomButtonStyle)style padding:(CGFloat)padding
{
    if (self.imageView.image == nil || self.titleLabel.text == nil) return self;
    
//    if (@available(iOS 15.0,*)) {
//        switch (style) {
//            case ImageRightPaddingTitleLeftWithWholeCenter:
//            {
//                UIButtonConfiguration *configuration = self.configuration;
//                configuration.imagePlacement = NSDirectionalRectEdgeTrailing;
//                configuration.imagePadding = padding;
//                self.configuration = configuration;
//                break;
//            }
//            case ImageTopPaddingTitleBottomWithWholeCenter:
//            {
//                UIButtonConfiguration *configuration = self.configuration;
//                if (configuration == nil) {
//                    configuration = [UIButtonConfiguration plainButtonConfiguration];
//                    self.configuration = configuration;
//                }
//                configuration.imagePlacement = NSDirectionalRectEdgeTop;
//                configuration.imagePadding = padding;
//                self.configuration = configuration;
//                break;
//            }
//            case ImageBottomPaddingTitleTopWithWholeCenter:
//            {
//                UIButtonConfiguration *configuration = self.configuration;
//                configuration.imagePlacement = NSDirectionalRectEdgeBottom;
//                configuration.imagePadding = padding;
//                self.configuration = configuration;
//                break;
//            }
//            case ImageLeftPaddingTitleRightWithWholeCenter:
//            {
//                UIButtonConfiguration *configuration = self.configuration;
//                configuration.imagePlacement = NSDirectionalRectEdgeLeading;
//                configuration.imagePadding = padding;
//                self.configuration = configuration;
//                break;
//            }
//            default:
//                break;
//        }
//    }else{
        // 这是最初的size
        CGSize imageSizeOrigin = [self.imageView sizeThatFits:CGSizeZero];
        CGSize titleSizeOrigin = [self.titleLabel sizeThatFits:CGSizeZero];
        CGSize fitSizeOrigin = [self sizeThatFits:CGSizeZero];

        // 这是向上取整后的size
        CGSize imageSize = CGSizeMake(ceilf(imageSizeOrigin.width), ceilf(imageSizeOrigin.height));
        CGSize titleSize = CGSizeMake(ceilf(titleSizeOrigin.width), ceilf(titleSizeOrigin.height));
        CGSize fitSize = CGSizeMake(ceilf(fitSizeOrigin.width), ceilf(fitSizeOrigin.height));

        // 最后的frame
        CGFloat finalFitWidth = 0.0;
        
        switch (style) {
            case ImageLeftPaddingTitleRightWithWholeCenter:
            {
                finalFitWidth = fitSize.width + padding;
                
                self.titleEdgeInsets = UIEdgeInsetsMake(0,
                                                        padding/2,
                                                        0,
                                                        -padding/2);
                
                self.imageEdgeInsets = UIEdgeInsetsMake(0,
                                                        -padding/2,
                                                            0,
                                                            padding/2);
            }
                break;
            case ImageRightPaddingTitleLeftWithWholeCenter:
            {
                finalFitWidth = fitSize.width + padding;
                
                self.titleEdgeInsets = UIEdgeInsetsMake(0,
                                                        -(imageSize.width + padding/2),
                                                        0,
                                                        (imageSize.width + padding/2));
                
                self.imageEdgeInsets = UIEdgeInsetsMake(0,
                                                        (titleSize.width + padding/2),
                                                        0,
                                                        -(titleSize.width + padding/2));
            }
                break;
            case ImageTopPaddingTitleBottomWithWholeCenter:
            {
                finalFitWidth = imageSize.width > titleSize.width ? imageSize.width : titleSize.width;
                // 这里的减掉 (selfSize.width - finalWidth) 是为了去掉边缘的margin，达到正好margin都是0的效果
                self.titleEdgeInsets = UIEdgeInsetsMake(titleSize.height/2.0+padding/2.0+(imageSize.height-titleSize.height)/2.0,
                                                        (titleSize.width + imageSize.width)/2.0 - (titleSize.width/2.0 + imageSize.width) - (fitSize.width - finalFitWidth),
                                                        -(titleSize.height/2.0+padding/2.0+(imageSize.height-titleSize.height)/2.0),
                                                        (titleSize.width/2.0 + imageSize.width) - (titleSize.width + imageSize.width)/2.0 - (fitSize.width - finalFitWidth) );
                
                self.imageEdgeInsets = UIEdgeInsetsMake(-(imageSize.height/2.0+padding/2.0-(imageSize.height-titleSize.height)/2.0),
                                                        (imageSize.width + titleSize.width)/2.0 - imageSize.width/2.0 - (titleSize.height/2.0 + padding) - (fitSize.width - finalFitWidth),
                                                        imageSize.height/2.0+padding/2.0-(imageSize.height-titleSize.height)/2.0,
                                                        imageSize.width/2.0 - (imageSize.width + titleSize.width)/2.0 - (titleSize.height/2.0 + padding) - (fitSize.width - finalFitWidth));
            }
                break;
            case ImageBottomPaddingTitleTopWithWholeCenter:
            {
                finalFitWidth = imageSize.width > titleSize.width ? imageSize.width : titleSize.width;
                // 这里的减掉 (selfSize.width - finalWidth) 是为了去掉边缘的margin，达到正好margin都是0的效果
                self.titleEdgeInsets = UIEdgeInsetsMake(-(titleSize.height/2.0 + padding/2.0),
                                                        (imageSize.width + titleSize.width)/2.0 - (titleSize.width/2.0 + imageSize.width) - (fitSize.width - finalFitWidth),
                                                        (titleSize.height/2.0 + padding/2.0),
                                                        (titleSize.width/2.0 + imageSize.width) - (imageSize.width + titleSize.width)/2.0 - (fitSize.width - finalFitWidth));
                
                self.imageEdgeInsets = UIEdgeInsetsMake((imageSize.height/2.0 - padding/2.0),
                                                        (imageSize.width + titleSize.width)/2.0 - imageSize.width/2.0 - (fitSize.width - finalFitWidth),
                                                        -(imageSize.height/2.0 - padding/2.0),
                                                        imageSize.width/2.0 - (imageSize.width + titleSize.width)/2.0 - (fitSize.width - finalFitWidth));
            }
                break;
            default:
                break;
        }
//    }
    
    return self;
}
@end
