//
//  HWMInputViewCell.m
//  HWMUISDKNativeDemo
//
//

#import "HWMInputViewCell.h"
#import "HWMTextField.h"

@interface HWMInputViewCell ()<NSTextFieldDelegate>

/// 输入框
@property (nonatomic, strong) HWMTextField *inputField;
/// 分割线
@property (nonatomic, strong) NSView *sepLine;

@end

@implementation HWMInputViewCell

+ (instancetype)initInputViewCell:(NSTableView *)tableView ower:(nullable id)ower {
    HWMInputViewCell *cell = [tableView makeViewWithIdentifier:NSStringFromClass([HWMInputViewCell class]) owner:ower];
    if (cell == nil) {
        cell = [[HWMInputViewCell alloc] initWithFrame:NSMakeRect(0, 0, 200, 50)];
        cell.identifier = NSStringFromClass([HWMInputViewCell class]);
    }
    return cell;
}

- (instancetype)initWithFrame:(NSRect)frameRect {
    if (self = [super initWithFrame:frameRect]) {
        self.wantsLayer = YES;
        self.layer.backgroundColor = [NSColor whiteColor].CGColor;
        [self setupUI];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.
}

#pragma mark - UI
- (void)setupUI {
    [self addSubview:self.inputField];
    [self addSubview:self.sepLine];
    
    [self.inputField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self).offset(120);
        make.trailing.equalTo(self).offset(-120);
        make.centerY.equalTo(self);
    }];
    
    [self.sepLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.inputField.mas_leading);
        make.trailing.equalTo(self.inputField.mas_trailing);
        make.top.equalTo(self.inputField.mas_bottom).offset(10);
        make.height.mas_equalTo(1);
    }];
}

#pragma mark - Delegate
- (void)controlTextDidChange:(NSNotification *)obj {
    if (self.inputViewDidEndEditerHandler) {
        self.inputViewDidEndEditerHandler(self.inputField.stringValue, self.index);
    }
}

#pragma mark - Setter
- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    self.inputField.placeholderString = placeholder;
}

- (void)setIndex:(NSInteger)index {
    _index = index;
}

- (void)setContent:(NSString *)content {
    _content = content;
    self.inputField.stringValue = content.length > 0 ? content : @"";
}

#pragma mark - Lazy
- (HWMTextField *)inputField {
    if (!_inputField) {
        _inputField = [[HWMTextField alloc] init];
        _inputField.delegate = self;
    }
    return _inputField;
}

- (NSView *)sepLine {
    if (!_sepLine) {
        _sepLine = [[NSView alloc] init];
        _sepLine.wantsLayer = YES;
        _sepLine.layer.backgroundColor = [NSColor colorWithRGB:0xEEEEEE].CGColor;
    }
    return _sepLine;
}

- (void)setEnabled:(BOOL)enabled {
    self.inputField.enabled = enabled;
}

- (BOOL)enabled {
    return self.inputField.enabled;
}
@end
