//
//  ViewController.m
//  SDK212
//
//  Created by woosimsystems on 2016. 7. 04..
//  Copyright © 2016년 woosimsystems. All rights reserved.
//
#import "RootViewController.h"
#import "WSSessionController.h"
#import "WSTableViewController.h"


NSString * woosimProtocolString = @"com.woosim.wspr240";

@implementation RootViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS 'WOOSIM M3X'"];
    //[[EAAccessoryManager sharedAccessoryManager] showBluetoothAccessoryPickerWithNameFilter:predicate completion:^(NSError *error) {
    //    if(error != nil && [error code] == EABluetoothAccessoryPickerResultCancelled)
    //    /* Cancel pressed */;
    //    if (error) {
    //        NSLog(@"error :%@", error);
    //    }
    //    else{
    //        NSLog(@"You make it! Well done!!!");
    //    }
    //}];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Create the view that gets shown when no accessories are connected
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
    [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
    
    _accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
    _sessionController = [[WSSessionController sharedController]init];
    

    
    
    [self.tableView reloadData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EAAccessoryDidDisconnectNotification object:nil];
    [[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications];
    
    if (_accessoryList != nil) _accessoryList = nil;
    if (_selectedAccessory != nil) _selectedAccessory = nil;
    if (_sessionController != nil) _sessionController = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    return [_accessoryList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell
    NSUInteger row = [indexPath row];
    NSString *accessoryName = [[_accessoryList objectAtIndex:row] modelNumber];
    
    if (!accessoryName || [accessoryName isEqualToString:@""]) accessoryName = @"unknown";
    
    [[cell textLabel] setText:accessoryName];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger row = [indexPath row];
    _selectedAccessory = [_accessoryList objectAtIndex:row];
    NSArray *protocolStrings = [_selectedAccessory protocolStrings];
    
    [[self tableView] deselectRowAtIndexPath:indexPath animated:YES];
    
    
    for(NSString *protocolString in protocolStrings) {
        // protocol string matching
        if ([protocolString isEqualToString:woosimProtocolString] || [protocolString isEqualToString:@"jp.star-m.starpro"]) {
            [_sessionController setupControllerForAccessory:_selectedAccessory withProtocolString:protocolString];
            
            if ([_sessionController openSession]) {
                
                NSLog(@"%@",_selectedAccessory);
                
                [self performSegueWithIdentifier:@"sampleSegue" sender:tableView];
                _selectedAccessory = nil;
                
                return;
            }else
            {
                NSLog(@"openSession fail ");
                
            }
        }
    }
    
    [self displayConnectAlertView];
    
}

-(void)displayConnectAlertView{
    
    UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:@"Warning"
                                  message:@"Selected accessory does not have specified protocol string."
                                  preferredStyle:UIAlertControllerStyleAlert];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
    
}

- (void)_accessoryDidConnect:(NSNotification *)notification
{
    NSLog(@"_accessoryDidConnect");
    // add new accessory to accessory list
    EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    [_accessoryList addObject:connectedAccessory];
    
    // update indexPath for added accessory
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([_accessoryList count] - 1) inSection:0];
    [[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification
{
    NSLog(@"_accessoryDidDisconnect");
    EAAccessory *disconnectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    
    // find index of disconnected accessory in accessory list
    int disconnectedAccessoryIndex = 0;
    for(EAAccessory *accessory in _accessoryList) {
        
        if ([disconnectedAccessory connectionID] == [accessory connectionID]) break;
        
        disconnectedAccessoryIndex++;
        
    }
    
    if (disconnectedAccessoryIndex < [_accessoryList count]) {
        // remove disconnected accessory from list
        [_accessoryList removeObjectAtIndex:disconnectedAccessoryIndex];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:disconnectedAccessoryIndex inSection:0];
        [[self tableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
    } else {
        NSLog(@"could not find disconnected accessory in accessory list");
    }
    
}



@end
