//
//  WMPostInputView.m
//  ZhengXing
//
//  Created by wangyang on 3/9/15.
//  Copyright (c) 2015 Wanmei Creative. All rights reserved.
//

#import "WMPostInputView.h"
#import "UIView+LineWithAutolayout.h"
#import "UIDevice+Resolutions.h"
#import "NSObject+KeyboardAnimation.h"
#import "HPGrowingTextView.h"
#import "UIView+SafeArea.h"

#define kTextViewH  36
@interface WMPostInputView () <HPGrowingTextViewDelegate>
{
    // inputArea包含_okButton和_textView。以方便移动
    UIView *_inputArea;
    HPGrowingTextView *_textView;
    GMButton *_sendButton;
    BOOL _editing;
}
@end

@implementation WMPostInputView

- (instancetype)init {
    if (self = [super init]) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange) name:UITextViewTextDidChangeNotification object:_textView.internalTextView];
    }
    return self;
}

- (void)setup{
    [super setup];

    self.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction)];
    [self addGestureRecognizer:tap];

    // inputArea包含若干个subview，以方便移动
    _inputArea = [UIView new];
    _inputArea.backgroundColor = UIColor.background;
    _inputArea.layer.cornerRadius = kTextViewH/2.0;
    _inputArea.clipsToBounds = YES;
    [self addSubview:_inputArea];
    [_inputArea addTopLine];

    _iconImgeView = [UIImageView new];
    _iconImgeView.layer.masksToBounds = YES;
    _iconImgeView.layer.cornerRadius = 25/2;
    _iconImgeView.image = [UIImage imageNamed:@"user_setter_default_icon_new"];
    [_inputArea addSubview:_iconImgeView];
    
    _textView = [HPGrowingTextView new];
    _textView.layer.cornerRadius = kTextViewH/2.0;
    _textView.backgroundColor = [UIColor clearColor];
    _textView.clipsToBounds = YES;
    _textView.delegate = self;
    _textView.font = [UIFont gmFont:13];
    _textView.textColor = UIColor.headlineText;
    _textView.returnKeyType = UIReturnKeySend;
    _textView.contentInset = UIEdgeInsetsMake(0, 2, 0, 0);
    _textView.internalTextView.textContainerInset = UIEdgeInsetsMake(10, 6, 10, 5);
    _textView.placeholderInsetes = UIEdgeInsetsMake(0, 7, 0, 0);
    _textView.minNumberOfLines = 1;
    _textView.maxNumberOfLines = 5;
    [_inputArea addSubview:_textView];

    _sendButton = [GMButton new];
    [_sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [_sendButton setTitleColor:RGBCOLOR_HEX(0x999999) forState:UIControlStateDisabled];
    [_sendButton setTitleColor:RGBCOLOR_HEX(0x0093FF) forState:UIControlStateNormal];
    [_sendButton setTitleColor:UIColor.auxiliaryTextLight forState:UIControlStateDisabled];
    _sendButton.titleLabel.font = [UIFont gmFont:16];
    [_sendButton addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
//    _sendButton.enabled = NO;
    [self addSubview:_sendButton];
    
    __weak __typeof(self)weakSelf = self;
    __weak __typeof(_inputArea)weakInputArea = _inputArea;
    [self observeKeyboardForView:_inputArea showKeyboardAnimation:^(CGRect keyboardFrame, CGFloat duration, NSInteger curve, NSNotification *notifcation) {

        [weakSelf mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-keyboardFrame.size.height);
        }];
        [UIView animateWithDuration:duration delay:0 options:curve animations:^{
            [weakSelf.superview layoutIfNeeded];
        } completion:NULL];

    } hideKeyboardAnimation:^(CGFloat duration, NSInteger curve, NSNotification *notifcation) {

        [weakSelf mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
        }];

        [UIView animateWithDuration:duration delay:0 options:curve animations:^{
            [weakSelf.superview layoutIfNeeded];
        } completion:^(BOOL finish){
        }];
    }];
}

- (void)updateConstraints
{
    CGFloat space = (kPostInputViewH - kTextViewH)/2;
    // _inputArea 利用 _textView 来自适应高度
    [_inputArea mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(_sendButton.mas_left);
        make.bottom.mas_equalTo(-space);
    }];
    
    [_sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(space);
        make.width.mas_equalTo(0);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(kTextViewH);
    }];
    
    CGFloat iconTop = (kTextViewH-25)/2;
    [_iconImgeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(iconTop);
        make.left.mas_equalTo(7);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
    
    [_textView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(_iconImgeView.mas_right);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo(kTextViewH);
    }];
    
    [super updateConstraints];
}

- (void)updateSendButton {
    
    CGFloat sendButtonW = 0;
    if ([_textView.text isNonEmpty] || _editing) {
        if ([_textView.text isNonEmpty]) {
            _sendButton.enabled = YES;
        } else {
            _sendButton.enabled = NO;
        }
        sendButtonW = 45;
    }
    
    if (_sendButton.frame.size.width == sendButtonW) {
        return;
    }
    [_sendButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(sendButtonW);
    }];
    [UIView animateWithDuration:0.3f animations:^{
        [self layoutIfNeeded];
    }];
}

- (void)textViewChange {
    [self updateSendButton];
}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(MAINSCREEN_WIDTH, 46);
}

- (void)dealloc{
    
    [self removeObservKeyboard];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Setter Getter
- (void)setPlaceHolder:(NSString *)placeHolder {
    _placeHolder = placeHolder;
    _textView.placeholder = placeHolder;
}

- (void)setText:(NSString *)text {
    _textView.text = text;
}

- (NSString *)text {
    return _textView.text;
}

#pragma mark - 键盘

- (void)hide
{
    [_textView resignFirstResponder];
}

- (void)show{
    
    self.hidden = NO;
    [_textView becomeFirstResponder];
    if (_textView.text.length > 0) {
        _textView.placeholder = @"";
    }
}

- (void)clear{
    _textView.text = @"";
}

#pragma mark - button 响应
- (void)cancelAction {
    if ([self.delegate respondsToSelector:@selector(inputViewWillCancel:)]) {
        [self.delegate inputViewWillCancel:self];
    }
    [self hide];
}

- (void)okAction{
    [_textView resignFirstResponder];
    if ([self.delegate respondsToSelector:@selector(inputView:sendText:)]) {
        [self.delegate inputView:self sendText:_textView.text];
    }
    [self hide];
}

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

#pragma mark - HPGrowingTextViewDelegate
- (BOOL)growingTextViewShouldBeginEditing:(HPGrowingTextView *)growingTextView {
    
    _editing = YES;
    [self beiginEditing];
    [self updateSendButton];
    return YES;
}

- (BOOL)growingTextViewShouldEndEditing:(HPGrowingTextView *)growingTextView {
    _editing = NO;
    [self updateSendButton];
    return YES;
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    [_textView mas_updateConstraints:^(MASConstraintMaker *make) {
        if (height > 35) {
            make.height.mas_equalTo(height);
        } else {
            make.height.mas_equalTo(35);
        }
    }];
}

-(BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView{
    [self okAction];
    return NO;
}

@end
