//
//  KKTextEditor.m
//  LIDONG
//
//  Created by Li Dong on 12-3-6.
//  Copyright (c) 2012年 LIDONG. All rights reserved.
//

#import "IBTextEditor.h"
#import "IBInternalTextView.h"

@interface IBTextEditor(PrivateMethods)
- (BOOL)constrainsToText;
@end

@implementation IBTextEditor

@synthesize backgroundImage = mBackgroundImage;
@synthesize delegate = mDelegate;

#define kPaddingX 2
#define kPaddingY 8
#define kMinNumberOfLines 1
#define kMaxNumberOfLines 5

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setBackgroundColor:[UIColor whiteColor]];
        [self setUserInteractionEnabled:YES];
        
        UIImage *image = [UIImage imageNamed:@"inputFrame.png"];
        CGSize imageSize = [image size];
        const int halfWidth = imageSize.width / 2.f;
        const int halfHeight = imageSize.height / 2.f;
        
        mNormalBackgroundImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(halfHeight, halfWidth, halfHeight, halfWidth)];
//        mHighlightedBackgroundImage = [mNormalBackgroundImage retain];
        
        CALayer *layer = [self layer];
        
        [layer setCornerRadius:5];
        [layer setBorderColor:[[UIColor darkGrayColor] CGColor]];
        [layer setBorderWidth:1.f];
        [layer setMasksToBounds:YES];
        
        UIFont *font = [UIFont systemFontOfSize:17];
        
        mInternalTextView = [[IBInternalTextView alloc] initWithFrame:CGRectZero];
        [mInternalTextView setDelegate:self];
        [mInternalTextView setBackgroundColor:[UIColor clearColor]];
        [mInternalTextView setContentInset:UIEdgeInsetsZero];
        [mInternalTextView setEditable:YES];
        [mInternalTextView setScrollEnabled:NO];
        [mInternalTextView setShowsHorizontalScrollIndicator:NO];
        [mInternalTextView setReturnKeyType:UIReturnKeySend];
        [mInternalTextView setFont:font];
        
        mLineHeight = font.ascender - font.descender;
        
        [self addSubview:mInternalTextView];
    }
    return self;
}

- (void)dealloc {
//    [mNormalBackgroundImage release];
//    [mHighlightedBackgroundImage release];
//    [mInternalTextView release];
//    [mPlaceHolderLabel release];
//    
//    [super dealloc];
}

- (void)drawRect:(CGRect)rect {
    [(mEditing ? mHighlightedBackgroundImage : mNormalBackgroundImage) drawInRect:[self bounds]];
}

- (void)didMoveToWindow {
    if ([self window]) {
        [self constrainsToText];
    }
}

- (void)calculateLayoutForPlaceHolderWithBounds:(CGRect)bounds {
    [mPlaceHolderLabel sizeToFit];
    
    CGRect placeHolderFrame = [mPlaceHolderLabel frame];
    
    placeHolderFrame.origin.x = bounds.origin.x + 8;
    placeHolderFrame.origin.y = bounds.origin.y + (bounds.size.height - placeHolderFrame.size.height) / 2.f;
    [mPlaceHolderLabel setFrame:placeHolderFrame];
}

- (void)layoutSubviews {
    const CGRect bounds = [self bounds];
    CGRect textFrame = { kPaddingX, 1, bounds.size.width - (kPaddingX << 1), bounds.size.height - 8 };
    
    [mInternalTextView setFrame:textFrame];
    
    [self calculateLayoutForPlaceHolderWithBounds:bounds];
    
    [self setNeedsDisplay];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [mInternalTextView becomeFirstResponder];
}

- (CGFloat)lineHeight {
    UIFont *font = [mInternalTextView font];
    
    return (font.ascender - font.descender + 1);
}

#pragma mark UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    [mInternalTextView setContentInset:UIEdgeInsetsZero];
    if ([mDelegate respondsToSelector:@selector(textEditorShouldBeginEditing:)]) {
        return [mDelegate textEditorShouldBeginEditing:self];
    }
	return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if ([mDelegate respondsToSelector:@selector(textEditorShouldEndEditing:)]) {
        return [mDelegate textEditorShouldEndEditing:self];
    }
	return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    mEditing = YES;
    if ([mDelegate respondsToSelector:@selector(textEditorDidBeginEditing:)]) {
        [mDelegate textEditorDidBeginEditing:self];
    }
    [self setNeedsDisplay];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    mEditing = NO;
    if ([mDelegate respondsToSelector:@selector(textEditorDidEndEditing:)]) {
        [mDelegate textEditorDidEndEditing:self];
    }
    [self setNeedsDisplay];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)newText {
    if ([mDelegate respondsToSelector:@selector(textEditor:shouldChangeTextInRange:replacementText:)]) {
        return [mDelegate textEditor:self shouldChangeTextInRange:range replacementText:newText];
    }
	return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
    if ([mDelegate respondsToSelector:@selector(textEditorDidChange:)]) {
        [mDelegate textEditorDidChange:self];
    }
    
    [self constrainsToText];
}

- (void)textEditorDidChangeSelection:(UITextView *)textView {
}

- (BOOL)constrainsToText {
    NSString *text = [mInternalTextView text];
//    UIFont *font = [mInternalTextView font];
    const NSInteger textLength = [text length];
//    const CGFloat maxTextWidth = self.bounds.size.width - kPaddingX * 2 - 10;
    const CGFloat lineHeight = mLineHeight + 1.f;
    const CGFloat minTextHeight = lineHeight * kMinNumberOfLines;
    const CGFloat maxTextHeight = lineHeight * kMaxNumberOfLines;
    
    [mPlaceHolderLabel setHidden:(textLength > 0)];
    
    CGFloat newTextHeight = lineHeight;
    
    if (0 < textLength) {
//        newTextHeight = [text sizeWithFont:font constrainedToSize:CGSizeMake(maxTextWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping].height;
        
        const int numberOfLines = (int)((newTextHeight / mLineHeight) + 0.75);
        newTextHeight = (int)(lineHeight * (CGFloat)numberOfLines + 0.75);
    }
    
    BOOL shouldScrollToEnd = fabs(newTextHeight - mLastTextHeight) >= mLineHeight;
    
    mLastTextHeight = newTextHeight;
    
    newTextHeight = (newTextHeight >= minTextHeight) ? newTextHeight : minTextHeight;
    newTextHeight = (newTextHeight <= maxTextHeight) ? newTextHeight : maxTextHeight;
    
    const CGFloat oldHeight = self.bounds.size.height;
    const CGFloat newHeight = roundf(newTextHeight + kPaddingY * 2);
    
    if (fabs(newHeight - oldHeight) >= 0.5) {
        [mInternalTextView setScrollEnabled:YES];
        
        if ([mDelegate respondsToSelector:@selector(textEditor:shouldResizeByHeight:)]) {
            [mDelegate textEditor:self shouldResizeByHeight:newHeight];
        }
    }
    return shouldScrollToEnd;
}

- (void)adjustSubviews {
    [mPlaceHolderLabel setHidden:[mInternalTextView hasText]];
    
    if ([self constrainsToText] && [mInternalTextView isScrollEnabled]) {
        [mInternalTextView setContentOffset:CGPointMake(1, mLastTextHeight)];
    }
}

- (NSString *)text {
    return [mInternalTextView text];
}

- (void)setText:(NSString *)newText {
    [mInternalTextView setText:newText];
    [self adjustSubviews];
}

- (void)insertText:(NSString *)text {
    // [UITextView insertText:]方法在设置输入焦点之前无效
    NSString *originalText = [mInternalTextView text];
    
    if (nil == originalText) {
        originalText = NSStringEmpty;
    }
    [self setText:[originalText stringByAppendingString:text]];
}

- (void)deleteBackward {
    [mInternalTextView deleteBackward];
    [self adjustSubviews];
}

- (BOOL)canBecomeFirstResponder {
    return [mInternalTextView canBecomeFirstResponder];
}

- (BOOL)becomeFirstResponder {
    return [mInternalTextView becomeFirstResponder];
}

- (BOOL)canResignFirstResponder {
    return [mInternalTextView canResignFirstResponder];
}

- (BOOL)resignFirstResponder {
    return [mInternalTextView resignFirstResponder];
}

- (BOOL)isFirstResponder {
    return [mInternalTextView isFirstResponder];
}

- (NSString *)placeHolder {
    return [mPlaceHolderLabel text];
}

- (void)setPlaceHolder:(NSString *)newPlaceHolder {
    if (newPlaceHolder && ![newPlaceHolder isEqualToString:NSStringEmpty]) {
        if (nil == mPlaceHolderLabel) {
            mPlaceHolderLabel = [[UILabel alloc] initWithFrame:CGRectZero];
            [mPlaceHolderLabel setBackgroundColor:[UIColor clearColor]];
            [mPlaceHolderLabel setTextColor:[UIColor lightGrayColor]];
            [mPlaceHolderLabel setTextAlignment:NSTextAlignmentLeft];
            [mPlaceHolderLabel setFont:[mInternalTextView font]];
            [mPlaceHolderLabel setAutoresizingMask:UIViewAutoresizingNone];
        }
        [mPlaceHolderLabel setText:newPlaceHolder];
        [self calculateLayoutForPlaceHolderWithBounds:[self bounds]];
        [self addSubview:mPlaceHolderLabel];
    } else if (mPlaceHolderLabel) {
//        UIVIEW_RELEASE_SAFELY(mPlaceHolderLabel);
    }
}

@end
