//
//  CustomLabelButton.m
//  OneCable
//
//  Created by Jason Lee on 1/7/16.
//  Copyright © 2016 ntels. All rights reserved.
//

#import "CustomLabelButton.h"
#import "UIButton+WebCache.h"
#import "CustomButton.h"
#import "CustomLabel.h"


@implementation CustomLabelButton

- (void)didMoveToSuperview {
    if (!self.superview)
        return;
    
    if (!_label) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self didMoveToSuperview];
        });
        return;
    }
    
    [_label addTouchEventHandler:^(id label) {
        [self labelTouched:label];
    }];
}

- (void)setTitle:(NSString *)title {
    _label.text = title;
}

- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
    
    [_btn sd_setImageWithURL:url forState:state placeholderImage:nil options:SDWebImageRefreshCached];
}

- (void)setEnabled:(BOOL)enabled {
    _btn.enabled = enabled;
    
    if (enabled) {
        if (!_label.touchHandler) {
            [_label addTouchEventHandler:^(id label) {
                [self labelTouched:label];
            }];
        }
    } else {
        _label.touchHandler = nil;
    }
}

#pragma mark - UIEvents

- (void)labelTouched:(id)sender {
    
    [_btn setHighlighted:YES];
    [_btn sendActionsForControlEvents:UIControlEventTouchUpInside];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kfAnimationDur * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_btn setHighlighted:NO];
    });
}

- (nullable NSArray<NSString *> *)actionsForTarget:(nullable id)target forControlEvent:(UIControlEvents)controlEvent {
    return [_btn actionsForTarget:target forControlEvent:controlEvent];
}

- (void)addTarget:(nullable id)target action:(nonnull SEL)action forControlEvents:(UIControlEvents)controlEvents {
    [_btn addTarget:target action:action forControlEvents:controlEvents];
    
    [_label addTouchEventHandler:^(id label) {
        [target performSelector:action withObject:nil];
    }];
}

@end
