//
//  ENSanDyGlucoseDevice.m
//  RNBTDevice
//
//  Created by lvwang2002 on 2019/5/12.
//  Copyright © 2019 zmxv. All rights reserved.
//

#import "ENSanDyGlucoseDevice.h"
@implementation ENSanDyGlucoseDevice{
    CBCharacteristic *_sendCharacteristic;
    NSString *connectedStatus;
    int requestCode;

}

const NSString *PREPARE = @"PREPARE";
const NSString *CREATING_CHANNEL = @"CREATING_CHANNEL";
const NSString *CREATED_CHANNEL = @"CREATED_CHANNEL";
const NSString *START_AUTHORIZATION = @"START_AUTHORIZATION";
const NSString *AUTHORIZATION_SUCCESSFUL = @"AUTHORIZATION_SUCCESSFUL";
const NSString *AUTHORIZATION_FAILED = @"AUTHORIZATION_FAILED";


static  NSString* UUID_BTLE_SERVICE = @"0000ffb0-0000-1000-8000-00805f9b34fb";
static  NSString* UUID_BTLE_SEND = @"0000ffb2-0000-1000-8000-00805f9b34fb";
static  NSString* UUID_BTLE_RECEIVE = @"0000ffb2-0000-1000-8000-00805f9b34fb";

const unsigned char SET = 0x61;
const unsigned char GET = 0x62;

const unsigned char VOLTAGE = 0X01;
const unsigned char DATA = 0x02;
//V09: 0X02
//V55: 0X03
//RECORD（日志）(only GET) 0X02
const unsigned char NDFI = 0x04;
const unsigned char ADFI = 0x05;
const unsigned char AD = 0x07;
const UInt8 AC = 0x06;

const unsigned char MONITOR = 0X08;
const unsigned char START = 0X01;
const unsigned char STOP = 0X03;
const UInt8 BATTERY = 0x11;
const UInt8 NAME = 0x0f;
const UInt8 SN = 0x13;
const UInt8 VERSION = 0x14;
const UInt8 AUTHO = 0x0B;



const unsigned char cmdStartMonitor[]={SET, MONITOR, START};
const unsigned char cmdStopMonitorp[] = {SET, MONITOR, STOP};
unsigned char cmdGetNumberDataFromIndex[] = {GET, NDFI, 0x00,0x00,0x00,0x00};
unsigned char cmdGetAllDataFromIndex[] = {GET,ADFI,0x00,0x00};
UInt8 cmdGetAllDataCount[] = {GET,AC};
UInt8 cmdGetAllData[] = {GET,AD};
UInt8 cmdGetBattery[] = {GET,BATTERY};
UInt8 cmdGetName[] = {GET,NAME};
UInt8 cmdGetSN[] = {GET,SN};
UInt8 cmdGetVersion[] = {GET,VERSION};
UInt8 cmdDoAuthorization[] = {GET,AUTHO,0x00,0x00,0x00,0x00,0x00,0x00};
UInt8 cmdGetMonitorStatus[] = {GET,MONITOR};


-(instancetype)initWithPeripheral:(CBPeripheral *)peripheral WithCentralManager:(CBCentralManager *)centerManager WithDevice:(BLEDevice *)device{
    self = [super initWithPeripheral:peripheral WithCentralManager:centerManager WithDevice:device];
    if(self){
        connectedStatus = [PREPARE copy];
        requestCode = 0;
    }
    return self;
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    //找到服务,开始扫描指定的服务
    NSArray *array = [peripheral services];
    
    for( CBService *service in array ){
        CBUUID *serviceUUID = [CBUUID UUIDWithString:UUID_BTLE_SERVICE];
        if([serviceUUID isEqual:service.UUID]){
            NSArray *uuids = @[[CBUUID UUIDWithString:UUID_BTLE_RECEIVE]];
            
            [peripheral discoverCharacteristics:uuids forService:service];
            break;
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error;{
    CBUUID *sendUUID = [CBUUID UUIDWithString:UUID_BTLE_SEND];
    CBUUID *receiveUUID = [CBUUID UUIDWithString:UUID_BTLE_RECEIVE];
    connectedStatus = [CREATING_CHANNEL copy];

    for( CBCharacteristic *characteristic in service.characteristics){
        NSString *log =[NSString stringWithFormat:@"characteristic is %@",characteristic];
        ENLog(log);
        
        if([characteristic.UUID isEqual:sendUUID]){
            _sendCharacteristic = characteristic;
        }
        
        if([characteristic.UUID isEqual:receiveUUID]){
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
    
    connectedStatus = [CREATED_CHANNEL copy];
    if([self.deviceDelegate respondsToSelector:@selector(onCreatedChannel:)]){
        [(id)self.deviceDelegate onCreatedChannel:_device];
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForReceiveData:(NSData *)data UUID:(CBUUID *)uuid error:(NSError *)error{
    CBUUID *receiveUUID = [CBUUID UUIDWithString:UUID_BTLE_RECEIVE];
    
    if( [receiveUUID isEqual:uuid]){
        Byte *command = (Byte *)[data bytes];
        NSLog(@"RNDY device rcv data:%@",data);
        NSLog(@"RNDY rcv data length:%lu",(unsigned long)[data length]);

        if([data length] == 9 && command[3]==0x63 && command[4]==0x00){
//           <0e240163 00150007 02>
//            <0e240163 00160007 02>
            UInt16 index =  command[6]*256+command[5];
            double value = (command[8]*256+command[7])/10.0;
            
            if([self.deviceDelegate respondsToSelector:@selector(onUpdateNewDataDevice:Index:ElecValue:)]){
                [(id)self.deviceDelegate onUpdateNewDataDevice:_device
                                                         Index:index
                                                     ElecValue:value];
            }
            

            return;
        }
        
        if(requestCode == 1){ //进入数据处理模式
//            <18021c02 22021f02 1f021c02 1c021c02 1f021c02>
            NSArray *array =[self byteToElecArray:command Length:[data length]];
                             
            if([self.deviceDelegate respondsToSelector:@selector(onGetProgressData:DataList:Index:)]) {
                [(id)self.deviceDelegate onGetProgressData:_device DataList:array Index:0];
            }
            
            return;
            
            
        }
        
        
        UInt8 CMD = (UInt8)command[4];
        switch (CMD) {
            //开始监控
            case MONITOR:{
                if(command[3] == GET){
                    bool isSuc = (command[5]==START);
                    if([self.deviceDelegate respondsToSelector:@selector(onGetMonitorStatus:IsStartMonitor:)]) {
                        [(id)self.deviceDelegate onGetMonitorStatus:_device IsStartMonitor:isSuc];
                    }
                }else{
                    UInt8 status = command[5];
                    if(status == START){
                        if([self.deviceDelegate respondsToSelector:@selector(onStartMonitor:IsSuc:)]){
                            [(id)self.deviceDelegate onStartMonitor:_device IsSuc:true];
                        }
                    }else if(status == STOP){
                        if([self.deviceDelegate respondsToSelector:@selector(onStopMonitor:IsSuc:)]){
                            [(id)self.deviceDelegate onStopMonitor:_device IsSuc:true];
                        }
                    }
                    
                }
                
            }
            break;
                
            case BATTERY:{
                double value = (command[2]*256+command[1])/100.0;
                if([self.deviceDelegate respondsToSelector:@selector(onGetBattery:Value:)]){
                    [(id)self.deviceDelegate onGetBattery:_device Value:value];
                }
            }
                break;
                
            //获取全部数据
            case NDFI:
            case ADFI:
            case AD:{
//                NSArray *array = [self byteToElecArray:&data[3] Length:[[characteristic value] length]];
                requestCode = 1;
                
            
            }
                break;
            case AC:{
                if([self.deviceDelegate respondsToSelector:@selector(onAuthenticated:IsSuc:)]){
//                    <0e260162 060000>
                    UInt16 count = [self bytesToIntHigh:command[6] Low:command[5]];
                    [(id)self.deviceDelegate onGetAllDataCount:_device Count:count];
                }
            }
                break;
            case AUTHO:{
                connectedStatus = [AUTHORIZATION_SUCCESSFUL copy];
                
                if([self.deviceDelegate respondsToSelector:@selector(onAuthenticated:IsSuc:)]){
                    [(id)self.deviceDelegate onAuthenticated:_device IsSuc:true];
                }
            }
                break;
            
                
        }
        
        
    }
    
}


-(void)parseUpdateData:(UInt8 *)data{
    UInt16 index = data[5]+data[6]*256;
    double elecValue = (data[7]+data[8]*256)/10.0;
    
    if([self.deviceDelegate respondsToSelector:@selector(onAuthenticated:IsSuc:)]){
        [(id)self.deviceDelegate
            onUpdateNewDataDevice:_device
                            Index:index
                         ElecValue:elecValue];
    }
    
    
    
}

/** 发送数据 */
-(void)sendData:(NSData *)data{
    if(_peripheral == nil || _sendCharacteristic == nil){
        //如果附件和属性有为空项,不发送.
        return;
    }
    NSLog(@"RNDY send data:%@",data);
    dispatch_async([[ENBLEDeviceManager shareDeviceManager] getPostQueue], ^{
        [_peripheral writeValue:data forCharacteristic:_sendCharacteristic type:CBCharacteristicWriteWithoutResponse];
    });
}

-(void)startMonitor{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdStartMonitor length:3];
    [self sendData:data];
}

-(void)stopMonitor{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdStopMonitorp length:3];
    [self sendData:data];
}


-(void)getNumberDataFromIndex:(UInt16)index Count:(UInt16)count{
    requestCode = 0;
    unsigned char numberArray[2];
    numberArray[0] = (unsigned char)(count>>8);
    numberArray[1] = (unsigned char)(count&0x00ff);
    
    unsigned char indexArray[2];
    indexArray[0] = (unsigned char)(index>>8);
    indexArray[1] = (unsigned char)(index&0x00ff);
    
    cmdGetNumberDataFromIndex[2] = numberArray[1];
    cmdGetNumberDataFromIndex[3] = numberArray[0];
    cmdGetNumberDataFromIndex[4] = indexArray[1];
    cmdGetNumberDataFromIndex[5] = indexArray[0];
    
    NSData *data = [NSData dataWithBytes:cmdGetNumberDataFromIndex length:6];
    [self sendData:data];
}

-(void)getAllDataFromIndex:(UInt16)index{
    requestCode = 0;
    UInt8 indexArray[2];
    indexArray[0] = (unsigned char)(index>>8);
    indexArray[1] = (unsigned char)(index&0x00ff);
    
    cmdGetAllDataFromIndex[2] = indexArray[1];
    cmdGetAllDataFromIndex[3] = indexArray[0];
    NSData *data = [NSData dataWithBytes:cmdGetAllDataFromIndex length:4];
    [self sendData:data];
}

-(void)getAllDataCount{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetAllDataCount length:2];
    [self sendData:data];
}

-(void)getAllData{
    requestCode = 1;
    NSData *data = [NSData dataWithBytes:cmdGetAllData length:2];
    [self sendData:data];
}

-(void)getBattery{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetBattery length:2];
    [self sendData:data];
}

-(void)getName{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetName length:2];
    [self sendData:data];
}

-(void)getSN{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetSN length:2];
    [self sendData:data];
}
-(void)getMonitorStatus{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetMonitorStatus length:2];
    [self sendData:data];
}
-(void)getMonitorVersion{
    requestCode = 0;
    NSData *data = [NSData dataWithBytes:cmdGetVersion length:2];
    [self sendData:data];
}

-(void)doAuthorization{
    connectedStatus = [START_AUTHORIZATION copy];
    NSData *data = [NSData dataWithBytes:cmdDoAuthorization length:8];
    [self sendData:data];
}

-(NSArray *)byteToElecArray:(UInt8 *)data Length:(UInt16)length{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for(int i=0;i<length;i=i+2){
        if(i==length-1){
            break;
        }
        UInt16 value = [self bytesToIntHigh:data[i+1] Low:data[i]];
        [array addObject:[NSNumber numberWithDouble:value/10.0]];
    }
    
    return [array copy];
}

-(UInt16)bytesToIntHigh:(UInt8)high Low:(UInt8)low{
    return high*256+low;
}

-(NSString *)getConnectedStatus{
    return connectedStatus;
}
@end
