//
//  OneViewController.m
//  MicroLifeDeviceSDK-Demo
//
//  Created by willy.wu on 2021/8/17.
//  Copyright © 2021 WiFi@MBP. All rights reserved.
//

#import "OneViewController.h"

@interface OneViewController ()

@end

@implementation OneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupKeyboardShowHide];
    kWeakSelf(self)
    [self.sdk getDidUpdateStateBlock:^(CBManagerState state) {
        NSString *log = [NSString stringWithFormat:@"DidUpdateState：%ld",(long)state];
        [weakself addLogWhitText:log];
    }];
    [self.sdk getScanDeviceBlock:^(NSInteger checkMacType, id  _Nonnull device) {
        NSString *log = [NSString stringWithFormat:@"ScanDevice Name：%@ UUID：%@ mac：%@ checkMacType：%ld",[device name],[device UUID],[device mac],checkMacType];
        [weakself addLogWhitText:log];
        if ([[device name] isEqualToString:weakself.deviceModel.text]) {
            [weakself connectDeviceInfo:device];
        }
    } CancelScanBlock:^() {
        [weakself addLogWhitText:@"Cancel Scan"];
    }];
    [self.sdk getConnectDeviceStateBlock:^(id  _Nonnull device, CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, CBPeripheralState state, NSError * _Nonnull error) {
        [weakself connectDeviceInfo:device PeripheralState:state];
        switch (state) {
            case CBPeripheralStateConnecting:
                [weakself.sdk cancelScan];
                break;
            case CBPeripheralStateConnected:
                if (weakself.servuceUUID.text.length > 0) {
                    [weakself.currDevice.currPeripheral discoverServices:@[[CBUUID UUIDWithString:weakself.servuceUUID.text]]];
                }
                break;
            case CBPeripheralStateDisconnected:
                [weakself.sdk startScan];
                break;
            default:
                break;
        }
    } CancelAllDevicesConnectionBlock:^{
        [weakself addLogWhitText:@"Cancel All Devices Connection"];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction
- (IBAction)connectDevice:(id)sender {
    if (self.currDevice) {
        [self.currDevice connectDevice];
    }
}
- (IBAction)disconnectDevice:(id)sender {
    if (self.currDevice) {
        [self.currDevice disconnectDevice];
    }
}
- (IBAction)writeValue:(id)sender {
    if (self.writeValue.text.length > 0 && self.writeUUID.text.length > 0) {
        [self.sdk writeValue:self.writeValue.text DeviceInfo:self.currDevice];
        [self addLogWhitText:[NSString stringWithFormat:@"WriteValue：%@",self.writeValue.text]];
    }
}

#pragma mark - DataResponseDelegate
- (void)connectDeviceInfo:(BLEDeviceInfo *)deviceInfo {
    [self addLogWhitText:@"Connect DeviceInfo"];
    self.currDevice = deviceInfo;
    [self.currDevice connectDevice];
    [self deviceInfoDelegate];
}

- (void)deviceInfoDelegate {
    kWeakSelf(self)
    [self.sdk getDiscoverServicesBlock:^(id  _Nonnull device, CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
        for (CBService *service in peripheral.services) {
            if (weakself.servuceUUID.text.length > 0) {
                if([service.UUID isEqual:[CBUUID UUIDWithString:weakself.servuceUUID.text]]){
                    [weakself.currDevice.currPeripheral
                     discoverCharacteristics:nil forService:service];
                }
            }
        }
    }];
    [self.sdk getDiscoverCharacteristicsBlock:^(id  _Nonnull device, CBPeripheral * _Nonnull peripheral, CBService * _Nonnull service, NSError * _Nonnull error) {
        for (CBCharacteristic *c in service.characteristics) {
            if (weakself.notiyUUID.text.length > 0) {
                if ([c.UUID isEqual:[CBUUID UUIDWithString:weakself.notiyUUID.text]]) {
                    weakself.currDevice.characteristicRx = c;
                    [weakself.sdk setNotifiy:weakself.currDevice characteristic:c];
                    [weakself addLogWhitText:@"notiy"];
                }
            }
            if (weakself.writeUUID.text.length > 0) {
                if ([c.UUID isEqual:[CBUUID UUIDWithString:weakself.writeUUID.text]]) {
                    weakself.currDevice.characteristicTx = c;
                    [weakself addLogWhitText:@"write"];
                }
            }
        }
    }];
    [self.sdk getWriteValueForCharacteristicBlock:^(CBCharacteristic * _Nonnull characteristic, NSError * _Nonnull error) {
        NSString *log = [NSString stringWithFormat:@"WriteValue：%@ error：%@",characteristic, error];
        [weakself addLogWhitText:log];
    }];
    [self.sdk getReadNotifyValueForCharacteristicBlock:^(id  _Nonnull device, CBPeripheral * _Nonnull peripheral, CBCharacteristic * _Nonnull characteristics, NSError * _Nonnull error) {
        [weakself writeRowData:characteristics.value];
        [weakself writeData:characteristics.value];
        NSString *log = [NSString stringWithFormat:@"length = %ld, bytes = %@\n",characteristics.value.length,characteristics.value.debugDescription];
        [weakself addLogWhitText:log];
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
