//
//  WEIViewController.m
//  MicroLifeDeviceSDK-Dome
//
//  Created by WiFi@ on 2018/5/18.
//  Copyright © 2018年 WiFi@MBP. All rights reserved.
//

#import "WEIViewController.h"


@implementation WEIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.ageTextField.text = self.currUser.age.stringValue;
    self.heightTextField.text = self.currUser.height.stringValue;
    self.weightTextField.text = self.currUser.weight.stringValue;
    self.genderSegmentedControl.selectedSegmentIndex = self.currUser.gender;
    self.userSegmentedControl.selectedSegmentIndex = self.currUser.userNo.integerValue;
    kWeakSelf(self)
    [self connectWeight];
    [self.sdk device:@[self.weight]];
    [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];
    } CancelScanBlock:^() {
        [weakself addLogWhitText:@"Cancel Scan"];
        [weakself.sdk startScan];
    }];
    [self.sdk getConnectDeviceStateBlock:^(id  _Nonnull device, CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, CBPeripheralState state, NSError * _Nonnull error) {
        [weakself connectDeviceInfo:device PeripheralState:state];
    } CancelAllDevicesConnectionBlock:^{
        [weakself addLogWhitText:@"Cancel All Devices Connection"];
        [weakself.sdk startScan];
    }];
}

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

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

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

#pragma mark - IBAction
- (IBAction)comAction:(UIButton *)sender {
    NSString *title = sender.titleLabel.text;
    switch (sender.tag) {
        case 100:
            [self.weight syncTiming];
            break;
        case 101:
            if (self.userSegmentedControl.selectedSegmentIndex != 0) {
                [self writeUserData];
            }
            break;
        case 102:
            [self.weight clearAllUsers];
            break;
        case 103:
            [self.weight readHistorys:self.currUser.userNo.integerValue ID:self.currUser.weightUserID];
            title = [title stringByAppendingFormat:@"Index:%@ ID:%@",self.currUser.userNo ,self.currUser.weightUserID];
            break;
        case 104:
            [self.weight queryVersion];
            break;
        case 105:
            [self.weight disconnect];
            break;
        case 106:
            [self.weight readUsers:self.userSegmentedControl.selectedSegmentIndex];
            title = [title stringByAppendingFormat:@" Index:%ld",self.userSegmentedControl.selectedSegmentIndex];
            break;
        default:
            break;
    }
    [self addLogWhitText:title];
}

- (void)writeUserData {
    if (self.currUser.userNo.integerValue != self.userSegmentedControl.selectedSegmentIndex) {
        self.currUser.userNo = @(self.userSegmentedControl.selectedSegmentIndex);
        self.currUser.weightUserID = [self getEBodyuserID];
        self.currUser.age = @([self getAge]);
        self.currUser.height = @([self getAge]+82);
        self.currUser.weight = @([self getAge]+2);
        self.ageTextField.text = self.currUser.age.stringValue;
        self.heightTextField.text = self.currUser.height.stringValue;
        self.weightTextField.text = self.currUser.weight.stringValue;
        [self saveNSUserDefaults:self.currUser.weightUserID Key:@"weightUserID"];
    }
    [self addLogWhitText:[NSString stringWithFormat:@"currUser: %@",self.currUser.parseDictionary]];
    [self.weight writeUserData:self.currUser.userNo.integerValue ID:self.currUser.weightUserID Age:self.currUser.age.integerValue Gender:self.currUser.gender Height:self.currUser.height.integerValue UnitType:self.currUser.unitType Weight:self.currUser.weight.floatValue Resistance:self.currUser.resistance.integerValue];
}

- (IBAction)value:(id)sender {
    if ([sender isEqual:self.ageTextField]) {
        self.currUser.age = @(self.ageTextField.text.integerValue);
    }
    else if ([sender isEqual:self.heightTextField]) {
        self.currUser.height = @(self.heightTextField.text.integerValue);
    }
    else if ([sender isEqual:self.weightTextField]) {
        self.currUser.weight = @(self.weightTextField.text.floatValue);
    }
    else if ([sender isEqual:self.genderSegmentedControl]) {
        self.currUser.gender = self.genderSegmentedControl.selectedSegmentIndex;
    }
}

#pragma mark - device
- (void)connectWeight {
    kWeakSelf(self)
    self.weight = [MicroLifeWS500 shareWhithAuthorizationkey:SDKkey_WEI];
    [self.weight addDeviceModel:@[@"Best Core BLE"]];
    [self.weight getValidationErrorBlock:^(NSString * _Nonnull item, NSString * _Nonnull info, id _Nonnull value) {
        [weakself addLogWhitText:[NSString stringWithFormat:@"item: %@\ninfo: %@\nvalue: %@",item,info,value]];
    }];
    [self.weight getReadDataModelBlock:^(NSInteger CMD, id  _Nonnull model, NSError * _Nonnull error) {
        switch (CMD) {
            case CMDWS500WakeUpScale:
                [weakself addLogWhitText:@"WakeUp Scale"];
                break;
            case CMDWS500SleepScale:
                [weakself addLogWhitText:@"Sleep Scale"];
                break;
            case CMDWS500MeasurementResult:
                [weakself addLogWhitText:@"Measurement Result"];
                [weakself scaleBleManagerDidReceiveMeasureResult:model];
                break;
            case CMDWS500ReadHistorys:
                [weakself addLogWhitText:@"Read Historys"];
                [weakself scaleBleManagerDidReceiveMeasureResult:model];
                break;
            case CMDWS500UpdateUserInfo:
                [weakself addLogWhitText:@"Update UserInfo"];
                break;
            case CMDWS500ClearAllUserInfo:
                [weakself addLogWhitText:@"Clear All UserInfo"];
                break;
            case CMDWS500UploadCompleted:
                [weakself addLogWhitText:@"Upload Completed"];
                break;
            case CMDWS500LowPower:
                [weakself addLogWhitText:@"Low Power"];
                break;
            case CMDWS500SyncSystemClock:
                [weakself addLogWhitText:@"Sync System Clock"];
                break;
            case CMDWS500ReadUserInfo:
                [weakself addLogWhitText:@"Read User Info"];
                [weakself updateUserInfo:model];
                break;
            default:
                break;
        }
        [weakself log:weakself.weight CMD:CMD Model:model Error:error];
    }];
}

- (void)updateUserInfo:(MicroLifeUserInfo *)user {
    self.currUser.userNo = user.userNo;
    self.currUser.weightUserID = user.weightUserID;
    self.currUser.age = user.age;
    self.currUser.height = user.height;
    self.currUser.weight = user.weight;
    self.currUser.gender = user.gender;
    self.currUser.resistance = user.resistance;
    self.userSegmentedControl.selectedSegmentIndex = self.currUser.userNo.integerValue;
}

- (void)scaleBleManagerDidReceiveMeasureResult:(MicroLifeBodyFat *)bodyFat {
    [bodyFat adjustAge:self.currUser.age Gender:self.currUser.gender Height:self.currUser.height];
    [self saveNSUserDefaults:bodyFat.resistance Key:@"resistance"];
    [self addLogWhitText:[NSString stringWithFormat:@"MicroLifeBodyFat:%@",bodyFat.parseDictionary]];
}
/*
 #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
