//
//  BTConnectViewController.m
//  AT188N_DEMO_1703
//
//  Created by 류은주 on 2017. 3. 2..
//  Copyright © 2017년 ATID. All rights reserved.
//

#import "BTConnectViewController.h"
#import "BLEConnectTableViewCell.h"
#import "EAScanDeviceItem.h"
#import "SWRevealViewController.h"

@interface BTConnectViewController ()
{
    BOOL bleready;
    BOOL btstate;
    BOOL devicestate;
    NSString * lastDeviceAddress;
    NSString * lastDeviceName;
    UIImage *connectdeviceimg;
    UIImage *connectstate;
    BOOL wrongdeviceflag;
    BOOL checkBtnState;
    NSMutableArray *aryDevices;
    
}
@property (weak, nonatomic) IBOutlet UILabel *appversionLabel;
@property (weak, nonatomic) IBOutlet UITableView *connectedtableview;

@end

@implementation BTConnectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    wrongdeviceflag = 0;
    _deviceInfo = [[DeviceSelectInfoDB alloc] init];
    aryDevices = [[NSMutableArray alloc] init];
    aryDevices = [_deviceInfo getArrayData];
    btstate = 0;
    checkBtnState = 1;
    self.appversionLabel.text = appDelegate.getAppVersion;
//    if(lastDeviceAddress==nil){
//        lastDeviceAddress = [_deviceInfo getBTInfoAddress];
//    }
//
//    appDelegate.latestdevicename = [_deviceInfo getBTInfoname];
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        
        mPeripherals = [NSMutableArray new];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            mQueue = dispatch_queue_create("com.atid.bluetooth", NULL);
            appDelegate.mCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:mQueue];
        });

    });
    
    
    
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    //appDelegate.mReader = nil;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(wrongdeviceconnected:) name:@"wrongdeviceconnected" object:nil];
    
    if (appDelegate.mReader == nil) {
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate.mReader setDelegate:self];
    }
    appDelegate.mCentralManager.delegate = self;
    
    //appDelegate.connectdeviceadd  = [_deviceInfo getBTInfoAddress];
    //appDelegate.connectdevicename = [_deviceInfo getBTInfoname];

   // lastDeviceName = appDelegate.latestdevicename;
//    [self getconnectedinfo];
    [self.connectedtableview reloadData];
    
}
-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [appDelegate.mCentralManager stopScan];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wrongdeviceconnected" object:nil];
    
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)getconnectedinfo:(NSString *)device {
    
    NSString *deviceName;
    deviceName = appDelegate.connectdevicename;

    NSString *deviceAddress;
    deviceAddress = appDelegate.connectdeviceadd;
    
//    lastDeviceName = deviceName;
    
    //if ((deviceName != nil)&&(deviceAddress != nil)) {
    if(device != nil){
        NSRange range1 = [device rangeOfString:@"AT188"];
        NSRange range2 = [device rangeOfString:@"AT288"];
        NSRange range3 = [device rangeOfString:@"AT388"];
        NSRange range4 = [device rangeOfString:@"ATS100"];
        
        
        if (range1.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at188.png"];
        }else if(range2.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at288.png"];
        }else if(range3.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at388.png"];
        }else if(range4.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_atsl.png"];
        }else {
            connectdeviceimg = [UIImage imageNamed:@"ic_unknown.png"];
        }
        
        if([device isEqualToString:deviceName]){
            if(appDelegate.mPeripheral.state == CBPeripheralStateConnected){
                connectstate = [UIImage imageNamed:@"btn_more_blue_normal.png"];
            }else {
                connectstate = [UIImage imageNamed:@"btn_more_red_normal.png"];
            }
        }else {
            connectstate = [UIImage imageNamed:@"btn_more_red_normal.png"];
        }
        
    } else{
        connectdeviceimg = [UIImage imageNamed:@"ic_unknown.png"];
        connectstate = [UIImage imageNamed:@"ic_unknown.png"];
    }
    
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.connectedtableview reloadData];
//    });
    
    checkBtnState = 1;
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return aryDevices.count;
}

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BLEConnectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConnectDeviceCell" forIndexPath:indexPath];
    
    DeviceSelectInfo * info = [aryDevices objectAtIndex:indexPath.row];
    [self getconnectedinfo:info.name];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0, 0.0, 65, 63);
    button.frame = frame;
    button.tag = indexPath.row;
    [button setBackgroundImage:connectstate forState:UIControlStateNormal];

        [button addTarget:self action:@selector(checkButtonTapped:)  forControlEvents:UIControlEventTouchUpInside];

    cell.accessoryView = button;
    
    [cell.deviceImg setImage:connectdeviceimg];
    [cell.devicestateImg setImage:connectstate];
    cell.devicenameLabel.text = info.name;

    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]
                                                initWithTarget:self action:@selector(deletelastconnect:)];
    recognizer.minimumPressDuration = 1.0; //seconds
    [cell addGestureRecognizer:recognizer];
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
     DeviceSelectInfo * info = [aryDevices objectAtIndex:indexPath.row];
    if(appDelegate.mPeripheral.state == CBPeripheralStateConnected){
        if([info.name isEqualToString:appDelegate.connectdevicename]){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self performSegueWithIdentifier:@"InventoryScan" sender:nil];
        });
        }
    }
    
}
- (void)deletelastconnect:(UILongPressGestureRecognizer *)gestureRecognizer{
    
    if(aryDevices.count<1)
        return;
    
    
    CGPoint p = [gestureRecognizer locationInView:self.connectedtableview];
    
    NSIndexPath *indexPath = [self.connectedtableview indexPathForRowAtPoint:p];
    
    DeviceSelectInfo * info = [aryDevices objectAtIndex:indexPath.row];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Delete" message:@"Do you want to delete the selected conntection?" preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
//                             appDelegate.connectdevicename = nil;
//                             appDelegate.connectdeviceadd = nil;
//                             appDelegate.latestdevicename = nil;
//                             lastDeviceName= nil;
                            
                             [_deviceInfo DeleteBTInfo:info.name macaddress:info.address];
//                             [self getconnectedinfo];
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 aryDevices = [_deviceInfo getArrayData];
                                 [self.connectedtableview reloadData];
                             });
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                             
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    if(![info.name isEqualToString:appDelegate.connectdevicename]){
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}

#pragma mark - CBCentralManagerDelegate Callbacks
/*!
 *  @constant CBCentralManagerStateUnknown       State unknown, update imminent.
 *  @constant CBCentralManagerStateResetting     The connection with the system service was momentarily lost, update imminent.
 *  @constant CBCentralManagerStateUnsupported   The platform doesn't support the Bluetooth Low Energy Central/Client role.
 *  @constant CBCentralManagerStateUnauthorized  The application is not authorized to use the Bluetooth Low Energy Central/Client role.
 *  @constant CBCentralManagerStatePoweredOff    Bluetooth is currently powered off.
 *  @constant CBCentralManagerStatePoweredOn     Bluetooth is currently powered on and available to use.
 */
// Update Central Manger State...
- (void) centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"DEBUG. BT Connect centeralManagerDidUpdateState:%d", (int)central.state);
    switch (central.state) {
        case CBManagerStateUnknown:
        case CBManagerStateResetting:
        case CBManagerStatePoweredOff:
            bleready = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"BluetoothDisconnected" object:self];
            //            [self BluetoothDisconnected];
            break;
        case CBManagerStateUnsupported:
        case CBManagerStateUnauthorized:
            break;
        case CBManagerStatePoweredOn:
            bleready = 1;
            //            [self startScanDevice];
            break;
        default:
            break;
            
    }
}

// Discover Peripheral Devices
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"centralManager.didDiscoverPeripheral : [%@]", peripheral.name);
    if([peripheral.name isEqualToString:lastDeviceName]){
        NSLog(@"centralManager.didDiscoverPeripheral : [%@]", peripheral.name);
        devicestate = 1;
    }
}

// Connected Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@"centralManager.didConnectPeripheral : [%@]", peripheral.name);
    
    mDevice = [[EADeviceBluetoothLe alloc] initWithPeripheral:peripheral delegate:self];
    
    appDelegate.mPeripheral = peripheral;
}

// Failed to Connect Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    if (error) {
        NSLog(@"ERROR. centralManager.didFailToConnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
        });
    } else {
        NSLog(@"centralManager.didFailToConnectPeripheral : [%@]", peripheral.name);
    }
    
    mDevice = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

// Disconnect Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    if (error) {
        NSLog(@"ERROR. centralManager.didDisconnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BluetoothDisconnected" object:self userInfo:nil];
        [self BluetoothDisconnected];
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            NSLog(@"ERROR. BTConnectViewController centralManager.didDisconnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        });
    } else {
        [self BluetoothDisconnected];
        NSLog(@"centralManager.didDisconnectPeripheral : [%@]", peripheral.name);
        
    }
    
    mDevice = nil;
}

#pragma mark - EABlEDeviceInitDelegate
- (void) didCompleteInitialize:(NSError *)error {
    if (error) {
        NSLog(@"ERROR. EABLEDevice.didCompleteInitialize : [%@]", error.localizedDescription);
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            return;
        });
        mDevice = nil;
    } else {
        NSLog(@"EABLEDevice.didCompleteInitialize");
    }
    [appDelegate.mCentralManager stopScan];
    appDelegate.mReader = [[EAReader alloc] initWithDevice:mDevice delegate:self.readerDelegate];
    
     checkBtnState = 1;
    appDelegate.maskstrvalue = @"";
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [HUD removeFromSuperview];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.connectedtableview reloadData];
        });
        
        if(wrongdeviceflag == 0){
            NSLog(@"didCompleteInitialize  InventoryScan");
            [self performSegueWithIdentifier:@"InventoryScan" sender:nil];
        }else {
            wrongdeviceflag = 0;
        }
    });
    
}

#pragma mark - Internal Methods

// Start Scan Peripheral BluetoothLE Device
- (void) startScanDevice {
    bleready = 1;
    devicestate = 0;
    //[self connectBLE];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    [appDelegate.mCentralManager scanForPeripheralsWithServices:nil options:options];
    
}
- (void) connectBLE {
    if (appDelegate.mPeripheral == nil){
        
        if(devicestate){
            
            HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            HUD.labelText = @"Connecting to device";
            
            //        [HUD show:YES];
            
            [self.navigationController.view addSubview:HUD];
            
            NSString *uuidString = [NSString stringWithFormat:@"%@",lastDeviceAddress];
            NSUUID *nsUUID = [[NSUUID UUID] initWithUUIDString:uuidString];
            NSArray *peripherallist;
            
            if(lastDeviceAddress != nil)
            {
                peripherallist = [appDelegate.mCentralManager retrievePeripheralsWithIdentifiers:@[nsUUID]];
            }
            
            if(peripherallist.count>0){
                [HUD show:YES];

                for(int i=0; i<[peripherallist count]; i++ )
                {
                    EAScanDeviceItem *item = [peripherallist objectAtIndex:i];
                    
                    NSString *itemstr = [NSString stringWithFormat:@"%@", item];
                    
                    NSRange range = [itemstr rangeOfString:lastDeviceName];
                    if (range.location != NSNotFound){
                        CBPeripheral *peripheral = [peripherallist objectAtIndex:i];
                        appDelegate.ConnectCentralManager = appDelegate.mCentralManager;
                        [appDelegate.mCentralManager connectPeripheral:peripheral options:nil];
                        
                        NSString * uuidString = [NSString stringWithFormat:@"%@", [[peripheral identifier] UUIDString]];
                        appDelegate.connectdevicename = [peripheral name];
                        appDelegate.connectdeviceadd = uuidString;
                        btstate = 1;
                        @synchronized (mPeripherals) {
                            [mPeripherals addObject:item];
                        }
//                        [self getconnectedinfo];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.connectedtableview reloadData];
                        });
                        return;
                        
                    }
                }
            }
        }else{
            //            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Device Power Off" message:@"Please check the power of device you want to connect" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            //            [alert show];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Device Power Off" message:@"Please check the power of device you want to connect" preferredStyle:UIAlertControllerStyleAlert];
            
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                                     [alert dismissViewControllerAnimated:YES completion:nil];
                                     checkBtnState = 1;
                                     
                                 }];
            [alert addAction:ok];
            
            
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    
}
- (void)disconnectDevice {
    if (appDelegate.mReader != nil) {
        [appDelegate.mReader disconnect];
    }
    appDelegate.mReader = nil;
    appDelegate.connectdevicename = @"";
    appDelegate.connectdeviceadd = @"";
    NSLog(@"appDelegate.mPeripheral %ld",(long)appDelegate.mPeripheral.state);
    // cc 종료 확인 필요........
    if(appDelegate.mPeripheral != nil){
        [appDelegate.ConnectCentralManager cancelPeripheralConnection:appDelegate.mPeripheral];
        
        NSLog(@"appDelegate.mPeripheral %ld",(long)appDelegate.mPeripheral.state);
        
        appDelegate.mPeripheral = nil;
    }
    btstate = 0;
    //devicestate = 0;
}
- (void)checkButtonTapped:(UIButton *)event
{
    if(event.tag == nil){
       [self deviceConnectChange:0];
    }else{
        [self deviceConnectChange:event.tag];
    }
}

- (void) deviceConnectChange:(int) cellrow {
    if(bleready==1){
        
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        [appDelegate.mCentralManager scanForPeripheralsWithServices:nil options:options];
        DeviceSelectInfo * item = [aryDevices objectAtIndex:cellrow];
        if(item.name != nil){
            if(appDelegate.mPeripheral == nil){
                wrongdeviceflag = 0;
                checkBtnState = 0;
                lastDeviceName = item.name;
                lastDeviceAddress = item.address;
                [self startScanDevice];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.7 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    [self connectBLE];
                });
                
            } else {
                if([item.name isEqualToString:appDelegate.connectdevicename]){
                    [self disconnectDevice];
                    //                [self getconnectedinfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.connectedtableview reloadData];
                    });
                }else {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Notice" message:@"Already connected with other device" preferredStyle:UIAlertControllerStyleAlert];
                    
                    
                    UIAlertAction* ok = [UIAlertAction
                                         actionWithTitle:@"OK"
                                         style:UIAlertActionStyleDefault
                                         handler:^(UIAlertAction * action)
                                         {
                                             [alert dismissViewControllerAnimated:YES completion:nil];
                                             
                                         }];
                    [alert addAction:ok];
                    
                    
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }
    }else{
        //        UIAlertView *Alert = [[UIAlertView alloc]
        //                              initWithTitle:@"ATX88N BT" message:@"BT is not power on" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        //        [Alert show];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"ATX88N BT" message:@"BT is not power on" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
        [alert addAction:ok];
        
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    NSLog(@"TableView Button Add TEST Success!!!!!");
}
//#pragma mark - NSNotification
//- (void)BluetoothDisconnected:(NSNotification *)notification {
- (void)BluetoothDisconnected {
    NSLog(@"BTConnectViewController - BluetoohDisconnected");
    wrongdeviceflag = 1;
    appDelegate.mReader = nil;
    appDelegate.mPeripheral = nil;
    [self disconnectDevice];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [HUD hide:YES];
        [HUD removeFromSuperview];
        [AppDelegate dismissGlobalHUD];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Bluetooth" message:@"Bluetooth device is disconnected" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BluetoothDisconnected" object:self];
        
         [self.connectedtableview reloadData];
    });
    
//    [self getconnectedinfo];
//    [self.connectedtableview reloadData];
    
}

- (void) wrongdeviceconnected:(NSNotification *)notification {
    NSLog(@"BTConnectViewController - wrongdeviceconnected");
    wrongdeviceflag = 1;
    [self disconnectDevice];
    
}
@end
