//
//  HWMSwitchCell.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2020/10/28.
//  Copyright © 2020 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMSwitchCell.h"
#import "HWMSwitch.h"

@interface HWMSwitchCell ()

/// 开关
@property (nonatomic, strong) HWMSwitch *rightBtn;
/// 标题
@property (nonatomic, strong) NSTextField *titleLabel;

@end

@implementation HWMSwitchCell

+ (instancetype)initSwitchCell:(NSTableView *)tableView ower:(id)ower {
    HWMSwitchCell *cell = [tableView makeViewWithIdentifier:NSStringFromClass([HWMSwitchCell class]) owner:ower];
    if (cell == nil) {
        cell = [[HWMSwitchCell alloc] initWithFrame:NSZeroRect];
        cell.identifier = NSStringFromClass([HWMSwitchCell class]);
    }
    return cell;
}

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

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}

#pragma mark - UI
- (void)setupUI {
    [self addSubview:self.titleLabel];
    [self addSubview:self.rightBtn];
    
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self).offset(-120);
        make.centerY.equalTo(self);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(18);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self).offset(120);
        make.trailing.equalTo(self.rightBtn.mas_leading).offset(-10);
        make.centerY.equalTo(self);
    }];
}

#pragma mark - Event
- (void)switchBtnClick:(HWMSwitch *)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(switchStateChanged:index:)]) {
        [self.delegate switchStateChanged:sender.checked index:self.index];
    }
}

#pragma mark - Setter
- (void)setIndex:(NSInteger)index {
    _index = index;
    
}

- (void)setTitle:(NSString *)title {
    _title = title;
    self.titleLabel.stringValue = title;
}

- (void)setState:(BOOL)state {
    _state = state;
    self.rightBtn.checked = state;
}

#pragma mark - Lazy
- (NSTextField *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [NSTextField hwm_fieldWithTitle:@"是否需要密码" titleColor:[NSColor colorWithRGB:0x666666] font:[NSFont systemFontOfSize:13]];
    }
    return _titleLabel;
}

- (HWMSwitch *)rightBtn {
    if (!_rightBtn) {
        _rightBtn = [[HWMSwitch alloc] init];
        _rightBtn.target = self;
        _rightBtn.action = @selector(switchBtnClick:);
    }
    return _rightBtn;
}

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

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