//
//  BluetoothController.m
//  MHTReceipt
//
//  Created by Mac on 2018/11/6.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "BluetoothController.h"
#import "BluetoothModel.h"
#import "BluetoothManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BluetoothUITableViewCell.h"

@interface BluetoothController ()

@property (strong,nonatomic) UILabel *bluetoothUILabel;

@property (strong,nonatomic) UITableView *bluetoothDeviceUITableView;

//蓝牙设备数组
@property (strong,nonatomic) NSMutableArray<BluetoothModel *>* bluetoothModels;

//蓝牙管理器
@property (strong,nonatomic) BluetoothManager *bluetoothManager;

@property (assign,nonatomic) CGFloat SCREEN_W;

@property (assign,nonatomic) CGFloat SCREEN_H;
@end

@implementation BluetoothController

- (void)viewDidLoad {
    [super viewDidLoad];
    _SCREEN_W = [UIScreen mainScreen].bounds.size.width;
    _SCREEN_H = [UIScreen mainScreen].bounds.size.height;
    [self initView];
    
    self.bluetoothModels = [NSMutableArray arrayWithCapacity:5];
    //获取一个蓝牙管理实例
    self.bluetoothManager = [BluetoothManager bluetoothManagerInstance];
    //初始化蓝牙回调（发送蓝牙设备回调，蓝牙连接成功回调）
    [self initBlock];
    //开始扫描蓝牙
    [self beginScan];
}

- (void)viewDidDisappear:(BOOL)animated{
    [self.bluetoothManager stopScan];
}

-(void)initBlock{
     __weak typeof(self) weakSelf = self;
    //发现蓝牙设备回调
    [self.bluetoothManager blePeripheralFound:^(CBPeripheral * _Nonnull peripheral) {
        NSString *uuid = peripheral.identifier.UUIDString;
        for(int i = 0; i < weakSelf.bluetoothModels.count;i++){
            BluetoothModel *bluetoothModel = weakSelf.bluetoothModels[i];
            NSString *tempUUID = bluetoothModel.peripheral.identifier.UUIDString;
            if([uuid isEqualToString:tempUUID]){
                return;
            }
        }
        
        BluetoothModel *bluetoothModel = [[BluetoothModel alloc] init];
        bluetoothModel.peripheral = peripheral;
        [weakSelf.bluetoothModels addObject:bluetoothModel];
        [weakSelf.bluetoothDeviceUITableView reloadData];
    }];
    //蓝牙连接成功回调
    [self.bluetoothManager blePeripheralConnected:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral) {
        NSLog(@"连接成功");
        [weakSelf dismissViewControllerAnimated:true completion:nil];
    }];
}

-(CGFloat)getRectNavAndStatusHight{
    return self.navigationController.navigationBar.frame.size.height+[[UIApplication sharedApplication] statusBarFrame].size.height;
}

-(void)initView{
    CGFloat endY = [self getRectNavAndStatusHight];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setTitleBar];
    endY = [self initBluetoothUILabel:endY];
    endY = [self initBluetoothDeviceUITableView:endY];
}

-(void)setTitleBar{
    self.title = @"蓝牙列表";
}


//开始扫描蓝牙设备
-(void)beginScan{
    [self.bluetoothModels removeAllObjects];
    [self.bluetoothManager beginScan];
}


-(CGFloat)initBluetoothDeviceUITableView:(CGFloat)startY{
    self.bluetoothDeviceUITableView = [[UITableView alloc] init];
    self.bluetoothDeviceUITableView.frame = CGRectMake(0, startY, _SCREEN_W, _SCREEN_H - startY);
    self.bluetoothDeviceUITableView.showsVerticalScrollIndicator = false;
    self.bluetoothDeviceUITableView.showsHorizontalScrollIndicator = false;
    self.bluetoothDeviceUITableView.delegate = self;
    self.bluetoothDeviceUITableView.dataSource = self;
    [self.view addSubview:self.bluetoothDeviceUITableView];
    
    return self.bluetoothDeviceUITableView.frame.origin.y + self.bluetoothDeviceUITableView.frame.size.height;
}

-(CGFloat)initBluetoothUILabel:(CGFloat)startY{
    self.bluetoothUILabel = [[UILabel alloc] init];
    self.bluetoothUILabel.frame = CGRectMake(10, startY, _SCREEN_W, 35);
    self.bluetoothUILabel.text = @"蓝牙列表";
    self.bluetoothUILabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:self.bluetoothUILabel];
    
    return self.bluetoothUILabel.frame.origin.y + self.bluetoothUILabel.frame.size.height;
}

//返回一个cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    int row = (int)indexPath.row;
    
    BluetoothModel *bluetoothModel = self.bluetoothModels[row];
    
    BluetoothUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[BluetoothUITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        [cell initUIView: CGSizeMake(_SCREEN_W, 50)];
    }
    NSString *name = bluetoothModel.peripheral.name;
    NSString *uuid = bluetoothModel.peripheral.identifier.UUIDString;
    [cell setData:name withUUID:uuid];
    return cell;
}

//返回cell的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.bluetoothModels.count;
}

//点击蓝牙设备item
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = (int)indexPath.row;
    BluetoothModel *bluetoothModel = self.bluetoothModels[row];
    //连接蓝牙
    [self.bluetoothManager connect:bluetoothModel.peripheral];
}

//返回高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

@end
