#import "DUREXAppViewController.h"
#import "EMFramework.h"
#import "CommunicationProtocol.h"

@interface DUREXAppViewController ()
{
    IBOutlet UIActivityIndicatorView *_activityIndicator;
    NSTimer *_writeTimer;
}
@property (nonatomic,strong) CommunicationProtocol* protocol;

@end

@implementation DUREXAppViewController

- (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:@"DUREX Vendor Control"];
    _protocol = [CommunicationProtocol sharedProtocol];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification:) name:kEMConnectionDidReceiveIndicatorNotificationName object:nil];
    [[EMConnectionManager sharedManager] addObserver:self forKeyPath:@"connectionState" options:0 context:NULL];
    [_protocol setMessageAvailable:false];
}

-(void)didReceiveNotification:(NSNotification*) notification
{
    id notificationValue = [[notification userInfo] objectForKey:kEMIndicatorResourceValueKey];
    NSString *resourceName = [[notification userInfo] objectForKey:kEMIndicatorNameKey];
    if([resourceName isEqualToString:@"messageAvailable"])
    {
        NSString *resourceValue = [notificationValue stringValue];
        if([resourceValue isEqualToString:@"TRUE"])
        {
            [_protocol setMessageAvailable:TRUE];
        }
        else
        {
            [_protocol setMessageAvailable:FALSE];
        }
    }
}

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

-(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




@end