//
//  EMBroadcastViewController.m
//  BroadcastExample
//
//  Created by Dexter Weiss on 12/17/13.
//  Copyright (c) 2013 Emmoco. All rights reserved.
//

#import "EMBroadcastViewController.h"
#import "EMFramework.h"

@interface EMBroadcastViewController () {
    IBOutlet UILabel *codeLabel;
    IBOutlet UILabel *firstDataField;
    IBOutlet UILabel *secondDataField;
}

@property (nonatomic, strong) EMDeviceBasicDescription *device;

@end

@implementation EMBroadcastViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[EMConnectionListManager sharedManager] addObserver:self forKeyPath:@"devices" options:0 context:NULL];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == [EMConnectionListManager sharedManager]) {
        if ([keyPath isEqualToString:@"devices"]) {
            NSArray *devices = [[EMConnectionListManager sharedManager] devices];
            [self setDevice:[devices lastObject]];
        }
    }
}

-(void)setDevice:(EMDeviceBasicDescription *)device {
    [self willChangeValueForKey:@"device"];
    _device = device;
    [self didChangeValueForKey:@"device"];
    [self _updateInterfaceForDevice];
}

-(void)_updateInterfaceForDevice {
    NSDictionary *broadcastInfo = [[self device] advertiseObject];
    NSString *code = [broadcastInfo objectForKey:@"c"];
    NSArray *values = [broadcastInfo objectForKey:@"d"];
    NSNumber *first = [values firstObject];
    NSNumber *second = [values lastObject];
    [codeLabel setText:code];
    [firstDataField setText:[NSString stringWithFormat:@"%0.1f", [first floatValue]]];
    [secondDataField setText:[NSString stringWithFormat:@"%0.1f", [second floatValue]]];
}

@end
