#import "EMFirstAppViewController.h"
#import "EMFramework.h"

@interface EMFirstAppViewController () {
    IBOutlet UIActivityIndicatorView *_activityIndicator;
    NSTimer *_writeTimer;
}

@end

@implementation EMFirstAppViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_activityIndicator setHidden:YES];
    [self setTitle:[[[EMConnectionManager sharedManager] connectedDevice] name]];
    [[EMConnectionManager sharedManager] readResource:@"data" onSuccess:^(id readValue) {
        [[self valueLabel] setText:[NSString stringWithFormat:@"%d", [readValue intValue]]];
        [[self valueSlider] setValue:[readValue floatValue]];
    } onFail:^(NSError *error) {
        
    }];
    
    [[EMConnectionManager sharedManager] addObserver:self forKeyPath:@"connectionState" options:0 context:NULL];
}

-(void)dealloc {
    [[EMConnectionManager sharedManager] removeObserver:self forKeyPath:@"connectionState"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == [EMConnectionManager sharedManager]) {
        if ([keyPath isEqualToString:@"connectionState"]) {
            if ([[EMConnectionManager sharedManager] connectionState] == EMConnectionStateDisrupted) {
                [[self navigationController] popToRootViewControllerAnimated:YES];
            }
        }
    }
}

#pragma mark - Interface actions

-(IBAction)sliderChanged:(UISlider *)sender {
    [[self valueLabel] setText:[NSString stringWithFormat:@"%0.0f", [sender value]]];
    if (_writeTimer) {
        [_writeTimer invalidate];
        _writeTimer = nil;
    }
    _writeTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(sliderDidFinishChanging:) userInfo:nil repeats:NO];
}

-(IBAction)sliderDidFinishChanging:(UISlider *)sender {
    [_writeTimer invalidate];
    _writeTimer = nil;
    [_activityIndicator startAnimating];
    [_activityIndicator setHidden:NO];
    
    [[EMConnectionManager sharedManager] writeValue:[NSNumber numberWithFloat:[[self valueSlider] value]] toResource:@"data" onSuccess:^{
        [_activityIndicator setHidden:YES];
        [_activityIndicator stopAnimating];
    } onFail:^(NSError *error) {
        
    }];
}
@end
