//
//  UIBarButtonItem+DDCategory.m
//  DDCategoryKit_Private
//  Created by DDIsFriend on 2023/2/6.

#import "UIBarButtonItem+DDCategory.h"

@implementation UIBarButtonItem (DDCategory)
+ (NSArray<UIBarButtonItem *> *)dd_barButtonItemsWithButtons:(NSArray<UIButton *> *)buttons itemPadding:(CGFloat)itemPadding placement:(DDBarButtonItemPlacement)placement{
    UIView *backgroundView = [UIView new];
    
    // offset为backgroundView整体向右的偏移量
    __block CGFloat offset = 0;
    __block CGFloat backgroundViewWidth = 0.0;
    __block CGFloat buttonInBackgroundViewX = 0.0;
    __block CGFloat maxHeight = 0.0;

    [buttons enumerateObjectsUsingBlock:^(UIButton * _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
        if (CGRectEqualToRect(btn.frame, CGRectZero)) {
            [btn sizeToFit];
        }
        CGFloat btnWidth = btn.frame.size.width;
        CGFloat btnHeight = btn.frame.size.height;
    
        btn.frame = CGRectMake(buttonInBackgroundViewX, 0, btnWidth, btnHeight);
        if (placement == DDBarButtonItemPlacementLeft) {
            btn.contentEdgeInsets = UIEdgeInsetsMake(0, -offset, 0, 0);
        }else if (placement == DDBarButtonItemPlacementRight){
            btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -offset);
        }
        [backgroundView addSubview:btn];
        
        // 两个按钮在barButtonItem上是有间隙的
        backgroundViewWidth = btnWidth + backgroundViewWidth + (idx != (buttons.count - 1) ? itemPadding : 0);
        buttonInBackgroundViewX = buttonInBackgroundViewX + btnWidth + offset + (idx != (buttons.count - 1) ? itemPadding : 0);
        if (btn.frame.size.height > maxHeight) {
            maxHeight = btn.frame.size.height;
        }
    }];
    backgroundView.frame = CGRectMake(0, 0, backgroundViewWidth, maxHeight);
    
    // 这个space会将整体的rightBarButtonItem向右偏移一段距离，大概是7,8个pt
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:backgroundView];
    
    return @[spaceItem,customItem];
}

@end
