//
//  MeatProbeVC.m
//  AILinkBleSDK_Example
//
//  Created by LarryZhang on 2023/3/7.
//  Copyright © 2023 zhengzida. All rights reserved.
//

#import "MeatProbeVC.h"
#import <AILinkBleSDK/ELAILinkBleManager+MeatProbe.h>
#import <AILinkBleSDK/ELMeatProbeBleTool.h>
#import "ELDemoButton.h"

@interface MeatProbeVC () <ELAILinkBleManagerDelegate>

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

@property (weak, nonatomic) IBOutlet UITextView *logTextView;

@property (nonatomic, strong) ELAILinkBleManager *bleManager;

@end


@implementation MeatProbeVC

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

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

#pragma mark - Action

- (IBAction)customDataRequestAction:(id)sender {
    NSData *payload = [self.bleManager meatProbeRequestCustomData];
    NSString *log = [NSString stringWithFormat:@"发: payload: %@", payload];
    [self addLog:log];
}

- (IBAction)customDataSendAction:(id)sender {
    NSData *payload = [self.bleManager meatProbeSendCustomData:[self coustumData]];
    NSString *log = [NSString stringWithFormat:@"发: payload: %@", payload];
    [self addLog:log];
}

- (IBAction)customDataClearAction:(id)sender {
    NSData *payload = [self.bleManager meatProbeSendCustomData:[NSData data]];
    NSString *log = [NSString stringWithFormat:@"发: payload: %@", payload];
    [self addLog:log];
}

- (IBAction)switchUnitAction:(id)sender {
    static BOOL flag = NO;
    if (flag) {
        NSData *payload = [self.bleManager meatProbeSwitchUint:0];
        NSString *log = [NSString stringWithFormat:@"发: payload: %@ -- 切换单位 to C", payload];
        [self addLog:log];
    } else {
        NSData *payload = [self.bleManager meatProbeSwitchUint:1];
        NSString *log = [NSString stringWithFormat:@"发: payload: %@ -- 切换单位 to F", payload];
        [self addLog:log];
    }
    flag = !flag;
}

- (IBAction)clearAction:(id)sender {
    self.logTextView.text = @"";
}

- (IBAction)shareLogAction:(id)sender {
}

- (NSData *)coustumData {
    //自定义数据
    //*******要验证设备必须支持128字节payload
    Byte bytes[128];
    memset(bytes, 0, sizeof(bytes));
    for (int i=0; i<sizeof(bytes); i++) {
        bytes[i] = 0x80 + i;
    }
    NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
    
    NSLog(@"meatProbeAction() data:%@", data);
    return data;
}

#pragma mark - ELAILinkBleManagerDelegate

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

- (void)scanBle {
    [self.bleManager scanFilterWithCidArray:@[@(self.per.cid)]];
}

- (void)connect {
    [self.bleManager connectAILinkPeripheral:self.per];
    [self updateBleStatusView:NELBleManagerConnectStateConnecting];
}

- (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 = @"蓝牙关闭";
        return;
    }
    switch (state) {
        case NELBleManagerConnectStateDisconnected:
            self.bleStatusLabel.text = @"断开连接";
            break;
        case NELBleManagerConnectStateFailed:
        case NELBleManagerConnectStateFailedValidation:
            self.bleStatusLabel.text = @"连接失败";
            break;
        case NELBleManagerConnectStateConnecting:
            self.bleStatusLabel.text = @"正在连接...";
            break;
        case NELBleManagerConnectStatePassed:
            self.bleStatusLabel.text = @"连接成功";
            
            //获取电量
            [self.bleManager getBluetoothInfoWithELInetGetCmdType:ELInetGetCmdTypeGetBatteryState];
            //获取 设置设备信息
//            [self requestDeviceData];
            break;
        case NELBleManagerConnectStateCentralScanning:
            self.bleStatusLabel.text = @"正在扫描...";
            break;

        default:
            break;
    }
}

- (void)requestDeviceData {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0), dispatch_get_main_queue(), ^{
        //获取 设置设备信息
        [self.bleManager meatProbeRequestCustomData];
    });
}

// 设备状态变更
- (void)managerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"%s state:%@", __func__, @(central.state));
    if (central.state == CBManagerStatePoweredOn) {
        [self scanBle];
    } else if (central.state == CBManagerStatePoweredOff) {
        [self updateBleStatusView: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);
    if ([peripheral.macAddressString isEqualToString:self.per.macAddressString]) {
        [self.bleManager stopScan];
        [self.bleManager connectAILinkPeripheral:peripheral];
    }
}

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

//A7数据
- (void)aiLinkBleReceiveA7Data:(NSData *)payload {
    NSLog(@"%s #### payload:%@", __func__, payload);
    ELMeatProbeBleTemperatureStruct temperatureInfo = [ELMeatProbeBleTool parseTemperature:payload];
    if (temperatureInfo.createTime == 0) {
        return;
    }
    
    NSString *log = [NSString stringWithFormat:@"internalTemprature:%@%@ (%@%@) ambientTemperature:%@%@ (%@%@)", @(temperatureInfo.internalTemperature_C), @"℃", @(temperatureInfo.internalTemperature_F), @"℉", @(temperatureInfo.ambientTemperature_C), @"℃", @(temperatureInfo.ambientTemperature_F), @"℉"];
    [self addLog:log];
}

//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);
        NSString *log = [NSString stringWithFormat:@"battery state:%@ power:%@", @(state), @(power)];
        [self addLog:log];
        return;
    }
    if (cmd == ELInetGetCmdTypeGetBMVersion) {
        NSString *bmVersion = self.bleManager.bmVersion;
        NSLog(@"##### bmVersion: %@", bmVersion);
        return;
    }
    if (cmd == ELInetGetCmdTypeGetBMVersionPro) {
        NSString *bmVersionPro = self.bleManager.bmVersionPro;
        NSLog(@"##### bmVersionPro: %@", bmVersionPro);
        return;
    }
    if (cmd == ELInetGetCmdTypeGetBasicInfoData) {
        NSLog(@"##### ELInetGetCmdTypeGetBasicInfoData: %@", packet);
        Byte state = bytes[3];
        if (state == 0x01) {
            NSData *custom = [packet subdataWithRange:NSMakeRange(4, 128)];
            NSString *log = [NSString stringWithFormat:@"custom:%@", custom];
            [self addLog:log];
        } else {
            NSString *log = [NSString stringWithFormat:@"custom:nil"];
            [self addLog:log];
        }
        return;
    }
}

#pragma mark - addLog

- (void)addLog:(NSString *)log {
    [self addLog:log newline:YES];
}

- (void)addWithoutNewlineLog:(NSString *)log {
    [self addLog:log newline:NO];
}

- (void)addLog:(NSString *)log newline:(BOOL)newline {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"HH:mm:ss.SSS";
    NSString *time = [format stringFromDate:[NSDate date]];
    if (newline) {
        self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@ %@\n", time, log];
    } else {
        self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@ %@", time, log];
    }
    [self.logTextView scrollRangeToVisible:NSMakeRange(self.logTextView.text.length, 1)];
}


@end
