//
//  ELDemoScanVC.m
//  AILinkBleSDK_Example
//
//  Created by LarryZhang on 2022/12/12.
//  Copyright © 2022 zhengzida. All rights reserved.
//

#import "ELDemoScanVC.h"
#import <AILinkBleSDK/ELAILinkBleManager.h>
#import "ELDeviceScanCell.h"
#import "ELDemoDeviceModel.h"

@interface ELDemoScanVC () <UITableViewDelegate, UITableViewDataSource, ELAILinkBleManagerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *bleStatusLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) ELAILinkBleManager *bleManager;

@property (nonatomic, assign) NELBleManagerConnectState bleConnectState;

@property (nonatomic, strong) NSMutableArray<ELAILinkPeripheral *> *peripheralArray;

@end

@implementation ELDemoScanVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.bleStatusLabel.text = @"";
    [self initBle];
}

- (void)dealloc {
    [self deinitBle];
}

- (IBAction)closeAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.peripheralArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ELDeviceScanCell *cell = [ELDeviceScanCell subsribeCell];
    
    ELAILinkPeripheral *per = self.peripheralArray[indexPath.row];
    
    cell.iconImageView.image = [UIImage imageNamed:self.demoDeviceModel.imageName];
    cell.cidValueLabel.text = [NSString stringWithFormat:@"0x%02X", per.cid];
    cell.vidValueLabel.text = [NSString stringWithFormat:@"0x%02X", per.vid];
    cell.pidValueLabel.text = [NSString stringWithFormat:@"0x%02X", per.pid];
    cell.macValueLabel.text = per.macAddressString;
    cell.rssiValueLabel.text = [NSString stringWithFormat:@"%@", per.RSSI];
    
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ELAILinkPeripheral *per = self.peripheralArray[indexPath.row];
    
    if (self.selectedBlock) {
        self.selectedBlock(per);
    }
     
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ELAILinkBleManagerDelegate

- (void)initBle {
    self.bleManager = [[ELAILinkBleManager alloc] init];
    self.bleManager.ailinkDelegate = self;
}

- (void)scanBle {
    self.peripheralArray = [NSMutableArray array];
    [self.bleManager scanFilterWithCidArray:self.cids];
}

- (void)deinitBle {
    [self.bleManager stopScan];
    self.bleManager.ailinkDelegate = nil;
    [self.bleManager disconnectPeripheral];
}

- (void)updateBleStatusView:(NELBleManagerConnectState)state {
    if (self.bleManager.central.state == CBManagerStatePoweredOff) {
        self.bleStatusLabel.text = @"Bluetooth: closed";
        return;
    }
    switch (state) {
        case NELBleManagerConnectStateDisconnected:
        case NELBleManagerConnectStateFailed:
        case NELBleManagerConnectStateFailedValidation:
            self.bleStatusLabel.text = @"Connect: failed";
            break;
        case NELBleManagerConnectStateCentralScanning:
            self.bleStatusLabel.text = @"Scanning...";
            break;
            
        default:
            break;
    }
}

// 设备状态变更
- (void)managerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"%s state:%@", __func__, @(central.state));
    if (central.state == CBManagerStatePoweredOn) {
        [self scanBle];
    } else if (central.state == CBManagerStatePoweredOff) {
        self.bleConnectState = NELBleManagerConnectStateCentralPowerOff;
    }
}

- (void)managerScanState:(BOOL)scanning {
    NSLog(@"%s scanning:%@", __func__, @(scanning));
    if (scanning) {
        [self updateBleStatusView:NELBleManagerConnectStateCentralScanning];
    }
}

// 扫描到设备
- (void)managerDidDiscoverPeripheral:(ELAILinkPeripheral *)peripheral {
    NSLog(@"managerDidDiscoverPeripheral cid:%02x vid:%02x pid:%02x mac:%@", peripheral.cid, peripheral.vid, peripheral.pid, peripheral.macAddressString);
    for (int i=0; i<self.peripheralArray.count; i++) {
        ELAILinkPeripheral *per = self.peripheralArray[i];
        if ([per.macData isEqualToData:peripheral.macData]) {
            self.peripheralArray[i] = per;
            [self.tableView reloadData];
            return;
        }
    }
    [self.peripheralArray addObject:peripheral];
    [self.peripheralArray sortUsingComparator:^NSComparisonResult(ELAILinkPeripheral *  _Nonnull obj1, ELAILinkPeripheral *  _Nonnull obj2) {
        if (obj1.RSSI.integerValue < obj2.RSSI.integerValue) return NSOrderedDescending;
        else if (obj1.RSSI.integerValue > obj2.RSSI.integerValue) return NSOrderedAscending;
        return NSOrderedSame;
    }];
    [self.tableView reloadData];
}

- (void)managerDidUpdateConnect:(NELBleManagerConnectState)state {
    NSLog(@"%s NELBleManagerConnectState:%@", __func__, @(state));
}


//A7数据
- (void)aiLinkBleReceiveA7Data:(NSData *)payload {
    NSLog(@"%s #### payload:%@", __func__, payload);
//    Byte *bytes = (Byte *)payload.bytes;
//    Byte cmd = bytes[0];
    
    
}

//A6数据
- (void)aiLinkBleReceiveA6Data:(NSData *)packet {
    NSLog(@"%s ##### packet:%@", __func__, packet);
    
    Byte *bytes = (Byte *)packet.bytes;
    Byte cmd = bytes[2];
    
    if (cmd == ELInetGetCmdTypeGetBatteryState) {
        int power = self.bleManager.battery.power;
        ELBatteryChargingState state = self.bleManager.battery.state;
        NSLog(@"##### state: %lu power: %d", (unsigned long)state, power);
    }
    if (cmd == ELInetGetCmdTypeGetBMVersion) {
        NSString *bmVersion = self.bleManager.bmVersion;
        NSLog(@"##### bmVersion: %@", bmVersion);
    }
    if (cmd == ELInetGetCmdTypeGetBMVersionPro) {
        NSString *bmVersionPro = self.bleManager.bmVersionPro;
        NSLog(@"##### bmVersionPro: %@", bmVersionPro);
    }

}

@end
