//
//  OCNavigationBar.m
//  Pods
//
//  Created by wangyang on 16/7/8.
//
//

#import "OCNavigationBar.h"
#import <Masonry/Masonry.h>
#import "GMBaseUtil.h"
@import GMKit;
@import SDWebImage;

@interface OCNavigationBarButton ()
@property (nonatomic, assign) CGFloat adaptiveWidth;
@end

@implementation OCNavigationBar {

}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, OCNavigationBar.barHeight)];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    [self setup];
}

- (void)setup{
    //设置一个初始值
    _buttonMargin = 20;

    self.clipsToBounds = NO;
    self.backgroundColor = [UIColor whiteColor];
    [self addNavigationShadow];

    _itemView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    CGFloat titleW = [UIScreen mainScreen].bounds.size.width - 80;
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, titleW, 44)];
    _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textColor = UIColor.headlineText;
    _titleLabel.font = [UIFont navigationFontWithSize:18];
    _leftButton = [OCNavigationBarButton buttonWithType:UIButtonTypeCustom];
    _rightButton = [OCNavigationBarButton buttonWithType:UIButtonTypeCustom];
    _nearRightButton = [OCNavigationBarButton buttonWithType:UIButtonTypeCustom];

    _titleLabel.hidden = YES;
    self.leftIcon = @"back";
    [self configBarButton:_leftButton];
    _leftButton.adaptiveWidth = 70;
    _leftButton.hidden = NO;
    [_leftButton addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self configBarButton:_rightButton];
    [_rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self configBarButton:_nearRightButton];
    [_nearRightButton addTarget:self action:@selector(nearRightAction:) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:_itemView];
    [_itemView addSubview:_titleLabel];
    [_itemView addSubview:_leftButton];
    [_itemView addSubview:_rightButton];
    [_itemView addSubview:_nearRightButton];
    [self updateButtonsConstraints];
}

- (void)updateButtonsConstraints {
    [_itemView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    [_leftButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_buttonMargin);
        make.centerY.mas_equalTo(0);
    }];
    [_rightButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-_buttonMargin);
        make.centerY.mas_equalTo(0);
    }];
    [_nearRightButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_rightButton.mas_left).offset(-_buttonMargin);
        make.centerY.mas_equalTo(0);
    }];
}

- (void)configBarButton:(OCNavigationBarButton *)button {
    UIColor *color = [UIColor colorWithhex:0x333333];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.hidden = YES;
    button.titleLabel.font = [UIFont navigationFontWithSize:16];
    button.adaptiveWidth = 40;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self layoutTitle];
}

/**
 限制标题视图的大小，不会盖住右边的button
 */
- (void)layoutTitle {
    if (_nearRightIcon || _nearRightTitle) {
        _titleLabel.frame = CGRectMake(80, 0, self.width - 160, 44);
        return;
    }

    if (_rightTitle.length >= 3 || _rightIcon) {
        _titleLabel.frame = CGRectMake(80, 0, self.width - 160, 44);
    }
}

#pragma mark - Public
- (void)hideAllItems {
    _titleLabel.hidden = YES;
    _leftButton.hidden = YES;
    _rightButton.hidden = YES;
    _nearRightButton.hidden = YES;
}

#pragma mark - Action
- (void)leftAction:(OCNavigationBarButton *)button {
    if ([self.delegate respondsToSelector:@selector(backAction:)]) {
        [self.delegate backAction:button];
    }
}

- (void)rightAction:(OCNavigationBarButton *)button {
    if ([self.delegate respondsToSelector:@selector(rightButtonClicked:)]) {
        [self.delegate rightButtonClicked:button];
    }
}

- (void)nearRightAction:(OCNavigationBarButton *)button {
    if ([self.delegate respondsToSelector:@selector(nearRightButtonClicked:)]) {
        [self.delegate nearRightButtonClicked:button];
    }
}

#pragma mark - Setter
- (void)setTitleView:(UIView * _Nullable)titleView {
    _titleView = titleView;
    if (titleView == nil) {
        [_titleView removeFromSuperview];
    } else {
        [_itemView insertSubview:_titleView atIndex:0];
        _titleView.center = CGPointMake(_itemView.bounds.size.width/2, _itemView.bounds.size.height/2);
    }
}
- (void)setTitle:(NSString *)title {
    _title = title;
    _titleLabel.hidden = NO;
    _titleLabel.text = _title;
    [self setNeedsLayout];
}

- (void)setLeftIcon:(NSString *)leftIcon {
    _leftIcon = leftIcon;
    _leftButton.hidden = NO;
    [_leftButton setImage:[UIImage imageNamed:_leftIcon] forState:UIControlStateNormal];
}

- (void)setRightIcon:(NSString *)rightIcon {
    _rightIcon = rightIcon;
    _rightButton.hidden = NO;
    [_rightButton setImage:[UIImage imageNamed:_rightIcon] forState:UIControlStateNormal];
    [self layoutTitle];
}

- (void)setLeftTitle:(NSString *)leftTitle {
    _leftTitle = leftTitle;
    _leftButton.hidden = NO;
    [_leftButton setImage:nil forState:UIControlStateNormal];
    [_leftButton setTitle:_leftTitle forState:UIControlStateNormal];
}

- (void)setRightTitle:(NSString *)rightTitle {
    _rightTitle = rightTitle;
    _rightButton.hidden = NO;
    [_rightButton setImage:nil forState:UIControlStateNormal];
    [_rightButton setTitle:_rightTitle forState:UIControlStateNormal];
    [self layoutTitle];
}

- (void)setNearRightIcon:(NSString *)nearRightIcon {
    _nearRightIcon = nearRightIcon;
    _nearRightButton.hidden = NO;
    [_nearRightButton setImage:[UIImage imageNamed:_nearRightIcon] forState:UIControlStateNormal];
    [self layoutTitle];
}

- (void)setNearRightTitle:(NSString *)nearRightTitle {
    _nearRightTitle = nearRightTitle;
    _nearRightButton.hidden = NO;
    [_nearRightButton setImage:nil forState:UIControlStateNormal];
    [_nearRightButton setTitle:_nearRightTitle forState:UIControlStateNormal];
    [self layoutTitle];
}

- (void)setNearRightIconURL:(NSString *)nearRightIconURL {
    _nearRightIconURL = nearRightIconURL;
    _nearRightButton.hidden = NO;
    
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:_nearRightIconURL] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (image) {
            UIImage *scaledImage = [image resizeToDeviceScale];
            [_nearRightButton setImage:scaledImage forState:UIControlStateNormal];
        }
    }];
    [self layoutTitle];
}

- (void)setRightIconURL:(NSString *)rightIconURL {
    _rightIconURL = rightIconURL;
    _rightButton.hidden = NO;
    
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:rightIconURL] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (image) {
            UIImage *scaledImage = [image resizeToDeviceScale];
            [_rightButton setImage:scaledImage forState:UIControlStateNormal];
        }
    }];
    
    [self layoutTitle];
}

- (void)setButtonMargin:(CGFloat)buttonMargin {
    _buttonMargin = buttonMargin;
    [self updateButtonsConstraints];
}

@end

@implementation OCNavigationBar (ViewConstant)
+ (CGFloat)barHeight {
    return [self statusBarHeight] + 44;
}

+ (CGFloat)statusBarHeight {
    CGFloat height = [[UIApplication sharedApplication] statusBarFrame].size.height;
    return height;
}

+ (CGFloat)navigationItemCenterY {
    return [self statusBarHeight] + 44/2.0;
}

@end
@implementation OCNavigationBarButton
/**
 *  @author wangyang in 2016-7-8 6.2.0
 *
 *  扩大导航栏热区响应
 */
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{

    //若原热区小于 _adaptiveHotAreaWidth x _adaptiveHotAreaHeight，则放大热区，否则保持原大小不变
    CGFloat widthDelta = MAX(self.adaptiveWidth - self.bounds.size.width, 0);
    CGFloat heightDelta = MAX(35 - self.bounds.size.height, 0);
    CGRect bounds = CGRectInset(self.bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(bounds, point);
}
@end
