//
//  IBTTextFieldCell.m
//  XFFruit
//
//  Created by Lili Wang on 15/4/3.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "IBTTextFieldCell.h"

@implementation IBTTextFieldCell

#pragma mark - Life Cycle
- (id)initWithStyle:(UITableViewCellStyle)style
    reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self _init];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect textFieldFrame = CGRectZero;
    if ([self.textLabel.text length] > 0) {
        self.textLabel.frame = ({
            CGRect frame = self.textLabel.frame;
            frame.size.width = MIN(MAX([self.textLabel sizeThatFits:CGSizeZero].width, JTLeftMinLabelWidth), JTLeftMinLabelWidth);
            frame;
        });
        
        CGFloat textFieldX = CGRectGetMaxX(self.textLabel.frame) + 5;
        textFieldFrame = (CGRect){
            .origin.x = textFieldX,
            .origin.y = 0,
            .size.width = CGRectGetWidth(_textField.superview.bounds) - IBT_GROUP_CELL_LEFT_PADDING - textFieldX,
            .size.height = CGRectGetHeight(_textField.superview.bounds)
        };
    }
    else {
        textFieldFrame = (CGRect){
            .origin.x = IBT_GROUP_CELL_LEFT_PADDING,
            .origin.y = 0,
            .size.width = CGRectGetWidth(_textField.superview.bounds) - IBT_GROUP_CELL_LEFT_PADDING * 2,
            .size.height = CGRectGetHeight(_textField.superview.bounds)
        };
    }
    
    _textField.frame = textFieldFrame;
}

- (void)updateTextIsIllegal:(BOOL)textIsIllegal {
    _textIsIllegal = textIsIllegal;
}

#pragma mark - Setter
- (void)setTextIsIllegal:(BOOL)textIsIllegal {
    _textIsIllegal = textIsIllegal;
    
    if (self.textLabel) {
        self.textLabel.textColor = _textIsIllegal ? [UIColor redColor] : [UIColor blackColor];
        self.textField.textColor = self.textLabel.textColor;
    }
    else {
        self.textField.textColor = _textIsIllegal ? [UIColor redColor] : [UIColor blackColor];
    }
}

#pragma mark - Private Method
- (void)_init {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.textField = [[IBTUITextField alloc] init];
    [self.contentView addSubview:_textField];
    
    [self.contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self.textField action:NSSelectorFromString(@"becomeFirstResponder")]];
}

@end
