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

#import "MeatProbeBoxVC.h"
#import <AILinkBleSDK/ELAILinkBleManager.h>
#import <AILinkBleSDK/NSData+AILinkBle.h>

#import "ELAILinkBleManager+MeatProbeBox.h"
#import "ELMeatProbeBoxBleParser.h"


@interface MeatProbeBoxVC () <ELAILinkBleManagerDelegate, ELMeatProbeBoxBleParserDelegate>

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

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


@property (nonatomic, strong) ELAILinkBleManager *bleManager;

@property (nonatomic, assign) NELBleManagerConnectState bleConnectState;

@property (nonatomic, strong) ELMeatProbeBoxBleParser *bleParser;

@property (nonatomic, strong) NSMutableSet *probeList;

@property (nonatomic, strong) ELMeatProbeBoxBleBoxStatusModel *boxStatus;

@end

@implementation MeatProbeBoxVC

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

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

#pragma mark - Action

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

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

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

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

- (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;
    self.bleParser = [[ELMeatProbeBoxBleParser alloc] init];
    self.bleParser.delegate = self;
    self.bleParser.mac = self.per.macAddressString;
}

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

- (void)connect:(ELAILinkPeripheral *)peripheral {
    [self.bleManager connectAILinkPeripheral:peripheral];
    [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 = @"蓝牙关闭";
        [self addLog: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 requestDeviceData];
            
            // read RSSI
//            [self readRSSI];
            
            break;
        case NELBleManagerConnectStateCentralScanning:
            self.bleStatusLabel.text = @"正在扫描...";
            break;

        default:
            break;
    }
    [self addLog:self.bleStatusLabel.text];
}

- (void)requestDeviceData {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0), dispatch_get_main_queue(), ^{
    });
}

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

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

//A7数据
- (void)aiLinkBleReceiveA7Data:(NSData *)payload {
    NSLog(@"%s #### payload:%@", __func__, payload.elHexString);
    NSString *log = [NSString stringWithFormat:@"收: payload: %@", payload.elHexString];
    [self addLog:log];
    
    [self.bleParser parseA7Payload:payload];
}

//A6数据
- (void)aiLinkBleReceiveA6Data:(NSData *)packet {
    NSLog(@"%s ##### packet:%@", __func__, packet.elHexString);
    
    Byte *bytes = (Byte *)packet.bytes;
    Byte cmd = bytes[2];
    
    if (cmd == ELInetGetCmdTypeGetBMVersion) {
        NSString *bmVersion = self.bleManager.bmVersion;
        NSLog(@"##### bmVersion: %@", bmVersion);
    }
    if (cmd == ELInetGetCmdTypeGetBMVersionPro) {
        NSString *bmVersionPro = self.bleManager.bmVersionPro;
        NSLog(@"##### bmVersionPro: %@", bmVersionPro);
    }
}

#pragma mark - ELMeatProbeBoxBleParserDelegate

//MCU 上报设备状态数据（Type：02）
- (void)meatProbeBoxBleParser:(ELMeatProbeBoxBleParser *)bleParser boxStatus:(ELMeatProbeBoxBleBoxStatusModel *)boxStatus probeStatus:(ELMeatProbeBoxBleProbeStatusModel *)probeStatus offline:(BOOL)offline {
    NSLog(@"##### boxStatus(): %@ probeStatus(): %@", boxStatus, probeStatus);
    self.boxStatus = boxStatus;
    NSString *log = [NSString stringWithFormat:@"boxStatus: { probeMaxCount:%hhu, probeCount:%hhu, batteryStatus:%hhu batteryPercent:%hhu, unit:%ld }", boxStatus.probeMaxCount, boxStatus.probeCount, boxStatus.batteryStatus, boxStatus.batteryPercent, boxStatus.unit];
    [self addLog:log];
    
    NSString *log2 = [NSString stringWithFormat:@"probeStatus: { index:%hhu, macString:%@, internalTemperature:%ld, ambientTemperature:%ld, batteryPercent:%hhu }", probeStatus.index, probeStatus.macString, probeStatus.internalTemperature, probeStatus.ambientTemperature, probeStatus.batteryPercent];
    [self addLog:log2];
    if (![self.probeList containsObject:probeStatus.macData]) {
        [self.probeList addObject:probeStatus.macData];
        NSData *payload = [self.bleManager meatProbeBoxRequestCustomDataWithMac:probeStatus.macData];
        NSString *log = [NSString stringWithFormat:@"发: payload: %@", payload];
        [self addLog:log];
    }
}

//设置、获取设备参数数据（Type：03）
- (void)meatProbeBoxBleParser:(ELMeatProbeBoxBleParser *)bleParser state:(BOOL)state mac:(NSData *)mac customData:(NSData *)customData {
    NSLog(@"##### state:%d mac:%@ customData():%@", state, mac, customData);
    NSLog(@"");
}

//切换单位（Type：04）
- (void)meatProbeBoxBleParser:(ELMeatProbeBoxBleParser *)bleParser unit:(ELDeviceTemperatureUnit)unit {
    NSLog(@"##### unit(): %@", @(unit));
    NSLog(@"");
}

- (void)peripheralDidReadRSSI:(nonnull NSNumber *)RSSI {
    NSLog(@"%s peripheralDidReadRSSI: %@", __FUNCTION__, RSSI);
    
    // main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        [self addLog:[NSString stringWithFormat:@"peripheralDidReadRSSI: %@", RSSI]];
    });
    
    [self readRSSI];
}

- (void)readRSSI {
    // delay
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // Read RSSI
        [self.bleManager readRSSI];
    });
}

#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
