1//
2//  KBPrefCheckbox.m
3//  Keybase
4//
5//  Created by Gabriel on 4/6/15.
6//  Copyright (c) 2015 Gabriel Handford. All rights reserved.
7//
8
9#import "KBPrefCheckbox.h"
10#import <Tikppa/Tikppa.h>
11
12@interface KBPrefCheckbox ()
13@property KBLabel *categoryLabel; // Optional
14@property KBButton *button;
15@property id<KBPreferences> preferences;
16@end
17
18@implementation KBPrefCheckbox
19
20- (void)viewInit {
21  [super viewInit];
22  _inset = 140;
23
24  _categoryLabel = [[KBLabel alloc] init];
25  [self addSubview:_categoryLabel];
26
27  _button = [KBButton button];
28  [self addSubview:_button];
29
30  YOSelf yself = self;
31  self.viewLayout = [YOLayout layoutWithLayoutBlock:^CGSize(id<YOLayout> layout, CGSize size) {
32    CGFloat x = 0;
33    CGFloat y = 0;
34    x += [layout sizeToFitVerticalInFrame:CGRectMake(x, y, yself.inset, 0) view:yself.categoryLabel].size.width + 10;
35
36    y += [layout sizeToFitVerticalInFrame:CGRectMake(x, y, size.width - x, 0) view:yself.button].size.height;
37    return CGSizeMake(size.width, y);
38  }];
39}
40
41- (void)dealloc {
42  [_button removeObserver:self forKeyPath:@"cell.state"];
43}
44
45- (void)setCategory:(NSString *)category {
46  [_categoryLabel setText:category style:KBTextStyleDefault alignment:NSRightTextAlignment lineBreakMode:NSLineBreakByClipping];
47}
48
49- (void)setLabelText:(NSString *)labelText identifier:(NSString *)identifier preferences:(id<KBPreferences>)preferences {
50  self.identifier = identifier;
51  self.preferences = preferences;
52  [_button setText:labelText style:KBButtonStyleCheckbox alignment:NSLeftTextAlignment lineBreakMode:NSLineBreakByTruncatingTail];
53
54  _button.state = [[self.preferences valueForIdentifier:identifier] boolValue] ? NSOnState : NSOffState;
55  [_button addObserver:self forKeyPath:@"cell.state" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
56
57  [self setNeedsLayout];
58}
59
60- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
61  BOOL value = [(NSButton *)object state] == NSOnState;
62  [self.preferences setValue:@(value) forIdentifier:self.identifier synchronize:YES];
63}
64
65@end
66