//
//  HygrothermographVC.m
//  AILinkBleSDK_Example
//

#import "HygrothermographVC.h"
#import <AILinkBleSDK/ELHygrothermographBleManager.h>
#import <AILinkBleSDK/ELHygrothermographBleRecordData.h>
#import <AILinkBleSDK/ELAILinkBleManager.h>
#import "ELDemoButton.h"

@interface HygrothermographVC () <ELBluetoothManagerDelegate, ELHygrothermographBleDelegate>

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

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


//work mode
@property (weak, nonatomic) IBOutlet ELDemoButton *weightModeButton;

@property (nonatomic, assign) ELBluetoothState state;

@end

@implementation HygrothermographVC

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

- (void)dealloc {
    [ELHygrothermographBleManager shareManager].delegate = nil;
    [ELHygrothermographBleManager shareManager].hygrothermographDelegate = nil;
    [[ELHygrothermographBleManager shareManager] disconnectPeripheral];
}

- (void)bleScan {
    //创建蓝牙
    [ELHygrothermographBleManager shareManager].delegate = self;
    [ELHygrothermographBleManager shareManager].hygrothermographDelegate = self;
    [[ELHygrothermographBleManager shareManager] startScan];
}

#pragma mark -Actions

- (IBAction)getDevStateAction:(id)sender {
    // /** 获取设备状态 */
    [[ELHygrothermographBleManager shareManager] getDevStateWithCid:self.per.cid];
}

- (IBAction)getDevHisDataAction:(id)sender {
    NSInteger maxDevTime = 0;
    [[ELHygrothermographBleManager shareManager] getDevRecordDataWithDevTime:maxDevTime cid:self.per.cid];
}


#pragma mark - addLog

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

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

- (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

#pragma mark - ble Delegate

@implementation HygrothermographVC (ble)

///返回设备连接状态
- (void)hygrothermographManagerUpdateState:(ELBluetoothState)state {
    NSLog(@"hygrothermograph ManagerUpdateState() state:%@", @(state));
    if (state == ELBluetoothStateDidValidationPass) {
        [self deviceInit];
    }
    
    NSString *text = nil;
    if (state == ELBluetoothStateScaning) {
        text = @"BLE connecting";
    } else if (state == ELBluetoothStateConnectFail) {
        text = @"BLE failed";
    } else if (state == ELBluetoothStateDidValidationPass) {
        text = @"BLE connected";
    } else if (state == ELBluetoothStateDidDisconnect) {
        text = @"BLE did disconnect";
    }
    
    if (text) {
        self.bleStatusLabel.text = text;
        if (self.state != state) {
            [self addLog:text];
        }
    }
    self.state = state;
}

///回调扫描到的温湿度计
- (void)hygrothermographManagerScanDevices:(NSArray<ELPeripheralModel *> *)scanDevices {
    for (ELPeripheralModel *model in scanDevices) {
        if ([model.macAddress isEqualToString:self.per.macAddressString]) {
            [[ELHygrothermographBleManager shareManager] stopScan];
            [[ELHygrothermographBleManager shareManager] connectPeripheral:model];
        }
    }
}

- (void)deviceInit {
    //同步时间
    [[ELHygrothermographBleManager shareManager] setUnixTime:[[NSDate date] timeIntervalSince1970]];
    
    // 获取设备支持的功能列表
    [[ELHygrothermographBleManager shareManager] getDevSupportFeaturesWithCid:self.per.cid];
    // APP获取设备报警功能
    [[ELHygrothermographBleManager shareManager] getDevAlarmDataInfoWithCid:self.per.cid];
    // 查询BM是否支持历史记录
    [[ELHygrothermographBleManager shareManager] getSupportRecordDataWithCid:self.per.cid];
}

// 设备返回当前状态
- (void)hygrothermographManagerReturnDevStatePower:(NSInteger)power bootTime:(long long)time tem:(float)tem hum:(float)hum {
    NSString *log = [NSString stringWithFormat:@"hygrothermograph power:%ld time:%lld tem:%f hum:%f", power, time, tem, hum];
    NSLog(@"%@", log);
    [self addLog:log];
}

// BM设备返回设备状态
- (void)newTHManagerReturnDevStatePower:(int)power bootTime:(long long)time tem:(float)tem unit:(enum ELDeviceTemperatureUnit)unit hum:(float)hum devState:(enum TH_DevStateType)state isCharging:(BOOL)isCharging {
    NSString *log = [NSString stringWithFormat:@"hygrothermograph power:%d time:%lld tem:%f unit:%ld hum:%f state:%ld", power, time, tem, (long)unit, hum, (long)state];
    NSLog(@"%@", log);
    [self addLog:log];
}

// 返回历史记录
- (void)hygrothermographManagerReturnRecordDataList:(NSArray<ELHygrothermographBleRecordData *> *)list allListNumber:(long long)allNumber getListNumber:(long long)getNumber {
    NSString *log = [NSString stringWithFormat:@"hygrothermograph list:%@ allListNumber:%lld getListNumber:%lld", list, allNumber, getNumber];
    NSLog(@"%@", log);
    [self addLog:log];
}

// 回应是否支持历史记录
- (void)THManagerSupportRecordData:(BOOL)state {
    NSString *log = state ? @"支持历史记录" : @"不支持历史记录";
    NSLog(@"hygrothermograph %@", log);
    
    [self addLog:log];
}

// 返回支持的功能列表
- (void)THManagerSuportList:(NSArray<NSNumber *> *)list {
    
    [self addLog:@"返回支持的功能列表"];
    for (NSNumber *number in list) {
        switch (number.intValue) {
            case TH_Dev_SupportFeatures_Calibration: {
                // 获取温度校准状态
                [[ELHygrothermographBleManager shareManager] setOrGetTemHumCalibrationValueWithSet:false cTem:0 fTem:0 hum:0 cid:self.per.cid];
            }
                break;
            case TH_Dev_SupportFeatures_BuzzerAlarm: {
                // 获取蜂鸣器报警状态，暂不支持
            }
                break;
            case TH_Dev_SupportFeatures_AlarmClock: {
                // 闹钟功能
                [[ELHygrothermographBleManager shareManager] setOrGetAlarmClockWithState:TH_AlarmClockState_Get num:0 mode:TH_AlarmClockMode_Everyday timeStr:@"00:00:00" open:false cid:self.per.cid];
            }
                break;
            case TH_Dev_SupportFeatures_ReportPunctually: {
                // 整点报时，暂不支持
            }
                break;
            case TH_Dev_SupportFeatures_NightLight: {
                // 获取小夜灯
                [[ELHygrothermographBleManager shareManager] setOrGetDevNightLightWithCmd:false open:false cid:self.per.cid];
            }
                break;
            case TH_Dev_SupportFeatures_GroundLight: {
                // 获取背光亮度
                [[ELHygrothermographBleManager shareManager] setOrGetGroundLightWithCmd:false open:false brightness:0 cid:self.per.cid];
            }
                break;
            case TH_Dev_SupportFeatures_Lost: {
                // 寻物功能
                
            }
                break;
                
            default:
                break;
        }
    }
    
}

/// 返回蜂鸣器设置结果
- (void)THManagerBuzzerState:(BOOL)open {
    NSString *log = open ? @"返回蜂鸣器: 开" : @"返回蜂鸣器: 关";
    [self addLog:log];
}

/// 返回闹钟列表
- (void)THManagerAlarmLockState:(enum TH_AlarmClockState)state num:(int)num mode:(enum TH_AlarmClockMode)mode timeStr:(NSString *)timeStr open:(BOOL)open {
    NSString *log = [NSString stringWithFormat:@"返回闹钟列表 %ld,%d,%ld,%@,%d", state, num, mode,timeStr, open ? 1 : 0];
    [self addLog:log];
}

/// 返回小夜灯
- (void)THManagerNightLightState:(BOOL)open {
    NSString *log = open ? @"返回小夜灯: 开" : @"返回小夜灯: 关";
    [self addLog:log];
}

/// 返回背光亮度
- (void)THManagerGounrdLightState:(BOOL)open brightness:(int)brightness {
    NSString *log = [NSString stringWithFormat:@"返回小夜灯: %@ brightness: %d", open ? @"开" : @"关", brightness];
    [self addLog:log];
}

/// 返回整点报时
- (void)THManagerReportPunctuallyState:(BOOL)open {
    NSString *log = open ? @"返回整点报时: 开" : @"返回整点报时: 关";
    [self addLog:log];
}

/// 设备返回当前单位
- (void)THManagerUnitState:(enum ELDeviceTemperatureUnit)unit {
    NSString *log = unit == 0 ? @"设备返回当前单位：℃" : @"设备返回当前单位：℉";
    [self addLog:log];
}

/// 设备返回温度校准值
- (void)hygrothermographManagerReturnCalibrationValueWithCelsiusTem:(float)celsiusCalibrationValue fahrenheitTem:(float)fahrenheitCalibrationValue hum:(float)humCalibrationValue {
    NSString *log = [NSString stringWithFormat:@"设备返回温度校准值 celsiusTem: %f fahrenheitTem: %f hum: %f", celsiusCalibrationValue, fahrenheitCalibrationValue, humCalibrationValue];
    [self addLog:log];
}

//返回阀值
- (void)hygrothermographManagerReturnThresholdTemThreshold:(float)tem humThreshold:(float)hum {
    
}

//返回设备信息
- (void)hygrothermographManagerReturnDevType:(enum Hygrothermograph_DevType)type version:(NSString *)version IMEI:(NSString *)IMEI {
    
}

//返回设备报警值
- (void)hygrothermographManagerReturnTemAlarmSwitch:(BOOL)temAlarm highTemAlarm:(float)highTem lowTemAlarm:(float)lowTem humAlarmSwitch:(BOOL)humAlarm highHumAlarm:(float)highHum lowHumAlarm:(float)lowHum {
    
    NSString *log = [NSString stringWithFormat:@"返回设备报警值 temAlarm:%@ highTem:%f lowTem:%f humAlarm:%@ highHum:%f lowHum:%f", temAlarm ? @"开" : @"关", highTem, lowTem, humAlarm ? @"开" : @"关", highHum, lowHum];
    [self addLog:log];
}


@end

