//
//  KBStreamOverlayView.m
//

#import "KBStreamOverlayView.h"
#import "KBStreamTextView.h"
#import "Masonry.h"

@interface KBStreamOverlayView ()
@property (nonatomic, strong) KBStreamTextView *textViewInternal;
@property (nonatomic, strong) UIButton *closeButton;
@end

@implementation KBStreamOverlayView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.92];
        self.layer.cornerRadius = 12.0; self.layer.masksToBounds = YES;

        [self addSubview:self.textViewInternal];
        [self addSubview:self.closeButton];

        [self.textViewInternal mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(0);
            make.right.equalTo(self.mas_right).offset(0);
            make.bottom.equalTo(self.mas_bottom).offset(0);
            make.top.equalTo(self.mas_top).offset(0);
        }];

        [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_top).offset(8);
            make.right.equalTo(self.mas_right).offset(-8);
            make.height.mas_equalTo(28);
            make.width.mas_greaterThanOrEqualTo(56);
        }];
    }
    return self;
}

- (KBStreamTextView *)textViewInternal {
    if (!_textViewInternal) {
        _textViewInternal = [[KBStreamTextView alloc] init];
    }
    return _textViewInternal;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        UIButton *del = [UIButton buttonWithType:UIButtonTypeSystem];
        del.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
        del.layer.cornerRadius = 14; del.layer.masksToBounds = YES;
        del.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold];
        [del setTitle:@"删除" forState:UIControlStateNormal];
        [del setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [del addTarget:self action:@selector(onTapClose) forControlEvents:UIControlEventTouchUpInside];
        _closeButton = del;
    }
    return _closeButton;
}

- (void)onTapClose {
    if ([self.delegate respondsToSelector:@selector(streamOverlayDidTapClose:)]) {
        [self.delegate streamOverlayDidTapClose:self];
    }
}

- (void)appendChunk:(NSString *)text {
    if (text.length == 0) return;
    [self.textViewInternal appendStreamText:text];
}

- (void)finish {
    [self.textViewInternal finishStreaming];
}

- (KBStreamTextView *)textView { return self.textViewInternal; }

@end

