//
//  BluetoothDeviceController.m
//  JXPrinterDemo
//
//  Created by 贾俊伟 on 2022/6/23.
//

#import "BluetoothDeviceController.h"
#import <JXPrinter/JXPrinter.h>
#import "PeripheralInfoCell.h"
#import "JXProgressHUD.h"

@interface BluetoothDeviceController ()<
JXBleManagerDelegate,
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *bottomBtn;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;

@property (nonatomic, strong) JXBleManager *manager;
@property (nonatomic, strong) NSMutableArray<PeripheralModel *> *peripherals;

@end

@implementation BluetoothDeviceController

static NSString * const cellId = @"cellId";
static NSString * const uuidStr = @"uuid";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomBtn];
    [self.bottomBtn addSubview:self.activityIndicator];
    [self.view addSubview:self.tableView];
    
    self.manager = [JXBleManager bleManager];
    self.manager.delegate = self;
    self.manager.useMTU = YES;
    [self p_startScanPeripherals];
    
    if (self.manager.centralManager.state == CBCentralManagerStatePoweredOff) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"OpenBluetooth", nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:done];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.activityIndicator.frame = CGRectMake(30, 0, 50, 50);
    self.bottomBtn.frame = CGRectMake(40, [UIScreen mainScreen].bounds.size.height - 100, [UIScreen mainScreen].bounds.size.width - 80, 50);
    self.tableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 120);
}

- (void)dealloc {
    NSLog(@"%s", __func__);
    [self.manager stopScan];
}

#pragma mark - JXBleManagerDelegate

- (void)manager:(JXBleManager *)manager centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"==========%@", @(central.state));
}

- (void)manager:(JXBleManager *)manager didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI address:(NSString *)address {
    NSLog(@"%s", __func__);
    PeripheralModel *model = [PeripheralModel modelWithPeripheral:peripheral address:address isSelected:(self.manager.connectedPeripheral.identifier == peripheral.identifier)];
    [self.peripherals addObject:model];
    [self.tableView reloadData];
}

- (void)scanTimeout:(JXBleManager *)manager {
    NSLog(@"%s", __func__);
    [self.bottomBtn setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
    [self.activityIndicator stopAnimating];
}

- (void)manager:(JXBleManager *)manager didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"%s", __func__);
    [JXProgressHUD hideHUD];
    for (PeripheralModel *model in self.peripherals) {
        model.isSelected = (model.peripheral.identifier == peripheral.identifier);
    }
    [self.tableView reloadData];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)manager:(JXBleManager *)manager didDisconnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"%s", __func__);
    for (PeripheralModel *model in self.peripherals) {
        if (model.peripheral == peripheral) {
            model.isSelected = NO;
            [self.tableView reloadData];
            return;
        }
    }
}

- (void)didFailToConnectPeripheral {
    NSLog(@"%s", __func__);
    [JXProgressHUD hideHUD];
}

#pragma UITableViewDelegate, UITableViewDataSource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PeripheralInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.model = self.peripherals[indexPath.row];
    __weak typeof(self) weakSelf = self;
    cell.connectBlock = ^(BOOL isConnect) {
        CBPeripheral *peripheral = weakSelf.peripherals[indexPath.row].peripheral;
        if (isConnect) {
            if (peripheral.state != CBPeripheralStateDisconnected) {
                [weakSelf.manager disconnectPeripheral:peripheral];
            }
        } else {
            [JXProgressHUD showHUD];
            if ([JXSocketManager manager].isConnected) {
                [[JXSocketManager manager] disconnect];
            }
            // 发起连接的命令
            [weakSelf.manager connectPeripheral:peripheral];
        }
    };
    return cell;
}

#pragma mark - Utils

- (void)p_startScanPeripherals {
    [self.manager scanPeripheralsWithWithServices:nil options:nil timeout:10 failure:nil];
    [self.bottomBtn setTitle:NSLocalizedString(@"Stop", nil) forState:UIControlStateNormal];
    [self.activityIndicator startAnimating];
    [self.peripherals removeAllObjects];
    [self.tableView reloadData];
}

- (void)p_stopScanPeripherals {
    [self.manager stopScan];
    [self.bottomBtn setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
    [self.activityIndicator stopAnimating];
}

- (void)bottomBtnClick {
    if (self.manager.centralManager.isScanning) {
        [self p_stopScanPeripherals];
    } else {
        [self p_startScanPeripherals];
    }
}

#pragma mark - Getter

- (NSMutableArray<PeripheralModel *> *)peripherals {
    if (!_peripherals) {
        _peripherals = [[NSMutableArray alloc] init];
    }
    return _peripherals;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PeripheralInfoCell class]) bundle:nil] forCellReuseIdentifier:cellId];
    }
    return _tableView;
}

- (UIButton *)bottomBtn {
    if (!_bottomBtn) {
        _bottomBtn = [[UIButton alloc] init];
        _bottomBtn.backgroundColor = [UIColor blueColor];
        [_bottomBtn addTarget:self action:@selector(bottomBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomBtn;
}

- (UIActivityIndicatorView *)activityIndicator {
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    }
    return _activityIndicator;
}

@end
