//
//  GMPlaceholderTextContainer.m
//  Gengmei
//
//  Created by wangyang on 16/1/5.
//  Copyright © 2016年 Wanmeichuangyi. All rights reserved.
//

#import "GMPlaceholderTextContainer.h"
#import <Masonry/Masonry.h>
//#import "NSString+GM.h"
#import "GMFont.h"
#import <UIColor+GMTheme.h>
#import <Constant.h>
@implementation GMPlaceholderTextContainer

- (void)setup
{
    [super setup];

    _placeholderOrigin = CGPointMake(6, 7);

    _textView = [UITextView new];
    _textView.font = [UIFont gmFont:15];
    [self addSubview:_textView];
    
    _placeholderLabel = [GMLabel labelWithTextColor: UIColor.disable fontSize:15];
    _placeholderLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:_placeholderLabel];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)updateConstraints{

    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

    [_placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_textView.mas_top).offset(_placeholderOrigin.y);
        make.left.equalTo(_textView.mas_left).offset(_placeholderOrigin.x);
    }];

    [super updateConstraints];
}

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

- (void)textViewDidChange{    
    NSMutableCharacterSet *emptyStringSet = [[NSMutableCharacterSet alloc] init];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"　"]];
    if ([_textView.text length] == 0) {
        _placeholderLabel.hidden = NO;
    }
    NSString* str = [_textView.text stringByTrimmingCharactersInSet:emptyStringSet];
    _placeholderLabel.hidden = [str length] > 0;
}

#pragma mark - 重写
- (BOOL)becomeFirstResponder{
    [_textView becomeFirstResponder];
    return YES;
}

- (BOOL)resignFirstResponder{
    [_textView resignFirstResponder];
    return [super resignFirstResponder];
}


#pragma mark - Setter、Getter
- (NSString *)text{
    return _textView.text;
}

- (void)setText:(NSString *)text {
    _textView.text = text;
    [self textViewDidChange];
}

- (NSString *)placeholder {
    return _placeholderLabel.text;
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholderLabel.text = placeholder;
}

@end
