//
//  YMNextGrowingInternalTextView.m
//  PCDBank
//
//  Created by Gusont on 2021/8/20.
//  Copyright © 2021 SLAiELTS. All rights reserved.
//

#import "YMNextGrowingInternalTextView.h"

@implementation YMNextGrowingInternalTextView

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

- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer
{
    self = [super initWithFrame:frame textContainer:textContainer];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeNotification:) name:@"UITextViewTextDidChangeNotification" object:self];
        self.placeholderDisplayLabel = [[UILabel alloc] init];
        self.placeholderDisplayLabel.numberOfLines = 0;
        self.placeholderDisplayLabel.adjustsFontSizeToFitWidth = YES;
        self.placeholderDisplayLabel.minimumScaleFactor = 0.4;
        [self addSubview:self.placeholderDisplayLabel];
    }
    return self;
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    if (self.didChange) {
        self.didChange();
    }
    [self updatePlaceholder];
}

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    if (self.didChange) {
        self.didChange();
    }
    [self updatePlaceholder];
}

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    if (self.didUpdateHeightDependencies) {
        self.didUpdateHeightDependencies();
    }
}

- (void)setTextContainerInset:(UIEdgeInsets)textContainerInset
{
    [super setTextContainerInset:textContainerInset];
    if (self.didUpdateHeightDependencies) {
        self.didUpdateHeightDependencies();
    }
}

- (void)setPlaceholderAttributedText:(NSAttributedString *)placeholderAttributedText
{
    self.placeholderDisplayLabel.attributedText = placeholderAttributedText;
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
//    let maxSize = bounds.inset(by: textContainerInset).size
    [super layoutSubviews];
    CGSize maxSize = self.frame.size;
    CGSize size = [self.placeholderDisplayLabel sizeThatFits:maxSize];
    size.height = MIN(size.height, maxSize.height);
    self.placeholderDisplayLabel.frame = CGRectMake(self.textContainerInset.left + 5, self.textContainerInset.top - 1, size.width, size.height);
}

- (void)textDidChangeNotification:(NSNotification *)notification
{
    [self updatePlaceholder];
    if (self.didChange) {
        self.didChange();
    }
}

- (void)updatePlaceholder
{
    [self.placeholderDisplayLabel setHidden:self.text.length ? YES : NO];
}

@end
