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

#import "RootViewController.h"
#import "CloudViewController.h"

@interface RootViewController ()
@property (nonatomic, strong) NSMutableAttributedString *logStr;

@property (weak, nonatomic) IBOutlet UIButton *cloudAPIBut;
@property (weak, nonatomic) IBOutlet UIButton *emailBut;

@property (nonatomic, copy  ) changedBlock   changedBlock;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    // Do any additional setup after loading the view.
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *appBVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    self.VersionNumber.text = [NSString stringWithFormat:@"V %@(%@)",appVersion,appBVersion];
    
    self.MicroLifeDeviceSDKVersionNumber.text = [NSString stringWithFormat:@"DeviceSDKVersionNumber：%.1f",MicroLifeDeviceSDKVersionNumber];
    
    [self setNavigationTitle];
    
    self.logView.editable = NO;
    self.logView.layoutManager.allowsNonContiguousLayout = NO;
    
    kMicroLifeDeviceSDKShowLog(YES)
    
    // Bluetooth scanner establishment
    self.sdk = [BLESDK share];
    
//    MicroLifeBloodPressureDRecord *DRecord = [MicroLifeBloodPressureDRecord new];
//        [DRecord analysis:DeviceType4GBP CMD:0x00 Data:@"00000501010000000000000000000000000000000000000000000000000000000000000000774D5D190518142400006F4B5C19051814250000734D5D190518142A00007B515919051814310000834D56190518143B0000" UUID:@"" Mac:nil ProtocolID:nil];
//    NSLog(@"DRecord:%@",DRecord.parseDictionary);
    
}

- (void)setNavigationTitle {
    self.navigationItem.title = self.menuInfo.title?:[NSString stringWithFormat:@"MicroLifeDeviceSDK v%.1f",MicroLifeDeviceSDKVersionNumber];
    UIColor *backgroundColor = self.menuInfo.backgroundColor?:[IdeabusToolBox ib_RainbowColor:ColorGolden];
    UIColor *titleColor = self.menuInfo.textColor?:[IdeabusToolBox ib_ComplementaryColor:backgroundColor Alpha:1.0];
    //navigation標題文字顏色
    NSDictionary *dic = @{NSForegroundColorAttributeName:titleColor};
    UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];
    barApp.backgroundColor = backgroundColor;
    barApp.shadowColor = backgroundColor;
    barApp.titleTextAttributes = dic;
    self.navigationController.navigationBar.scrollEdgeAppearance = barApp;
    self.navigationController.navigationBar.standardAppearance = barApp;
    self.navigationController.navigationBar.tintColor = titleColor;
}

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

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

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

- (MicroLifeUserInfo *)currUser {
    if (!_currUser) {
        MicroLifeUserInfo *user = [MicroLifeUserInfo new];
        user.bpmUserID = [self readNSUserDefaults:@"bpmUserID"]?:[self getBPMuserID];
        user.pfmUserID = [self readNSUserDefaults:@"pfmUserID"]?:[self getBPMuserID];
        user.weightUserID = [self readNSUserDefaults:@"weightUserID"]?:[self getEBodyuserID];
        user.userNo = @(1);
        user.age = @(40);
        user.height = @(168);
        user.weight = @(70);
        user.gender = arc4random_uniform(1);
        user.resistance = [self readNSUserDefaults:@"resistance"]?:@(0);
        user.unitType = MicroLifeEBUnitTypeKG;
        _currUser = user;
    }
    return _currUser;
}

- (NSMutableAttributedString *)logStr {
    if (!_logStr) {
        self.logStr = [[NSMutableAttributedString alloc] init];
    }
    return _logStr;
}

- (NSString *)date {
    return [IdeabusToolBox ib_CurrentDateWithFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
}

- (void)clearLogStr {
    self.logStr = [[NSMutableAttributedString alloc] initWithString:@""];
    [self addLogWhitText:@"DEMO"];
    [self.logView scrollRangeToVisible:NSMakeRange(0, 0)];
}

// 需要在 @interface 中新增一個屬性來儲存累積的屬性字串
- (void)addLogWhitText:(NSString *)text {
    // 1. 先寫入檔案 (保持原有邏輯)
    [self writeData:text];
    
    // 2. UI 操作切回主執行緒
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view endEditing:true];
        NSLog(@"\n%@", text);
        
        // 3. 準備當前的時間與文字
        NSString *newLogString = [NSString stringWithFormat:@"%@\n%@\n***\n", self.date, text];
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newLogString];
        
        // 4. 設定基礎字體 (重要！設定 attributedText 時字體容易跑掉，建議固定)
        UIFont *font = [UIFont systemFontOfSize:14.0]; // 或 self.logView.font
        [attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attrString.length)];
        
        // 5. 判斷是否為錯誤訊息，進行「特殊高亮」
        if ([text containsString:@"[Validation Error]"]||[text containsString:@"Error:"]) {
            
            BOOL isDarkMode = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
            
            // A. 取得隨機文字顏色
            // 注意：這裡依據您的邏輯，深色模式用深色字(ColorDarkBlack)，淺色模式用亮色字(ColorBright)
            // 因為後面會配上互補色當背景，所以這樣對比度是沒問題的
            UIColor *textColor = [IdeabusToolBox ib_HSBRainbowColor:isDarkMode ? ColorDarkBlack : ColorBright Alpha:1.0];
            
            // B. 取得互補背景色 (使用我們剛寫好的完美版)
            UIColor *bgColor = [IdeabusToolBox ib_ComplementaryColor:textColor Alpha:0.5]; // 背景半透明一點比較好看
            
            // C. 設定文字顏色屬性
            [attrString addAttribute:NSForegroundColorAttributeName
                               value:textColor
                               range:NSMakeRange(0, attrString.length)];
            
            // D. 設定背景顏色屬性 (這就是 HighLight 重點)
            [attrString addAttribute:NSBackgroundColorAttributeName
                               value:bgColor
                               range:NSMakeRange(0, attrString.length)];
            
        } else {
            // 6. 正常訊息：根據日夜模式設定預設文字顏色
            UIColor *normalColor = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) ? [UIColor whiteColor] : [UIColor blackColor];
            
            [attrString addAttribute:NSForegroundColorAttributeName
                               value:normalColor
                               range:NSMakeRange(0, attrString.length)];
        }
        
        // 8. 拼接新的 Log
        [self.logStr appendAttributedString:attrString];
        
        // 9. 更新 UI
        self.logView.attributedText = self.logStr;
        
        // 10. 自動捲動到底部
        if (self.logView.text.length > 0) {
            NSRange bottomRange = NSMakeRange(self.logView.text.length - 1, 1);
            [self.logView scrollRangeToVisible:bottomRange];
        }
    });
}

- (NSString *)getBPMuserID {
    NSMutableString* BPMuserID = [[NSMutableString alloc] init];
    for (int i = 0; i < 11; i++) {
        if(i < 9){
            [BPMuserID appendString:[NSString stringWithFormat:@"%d", arc4random_uniform(10)]];
        } else {
            NSString *str = @"QWERTYUIOPASDFGHJKLZXCVBNM";
            [BPMuserID appendString:[NSString stringWithFormat:@"%@",[str substringWithRange:NSMakeRange(arc4random_uniform(26), 1)]]];
        }
    }
    return BPMuserID;
}

- (NSString *)getEBodyuserID {
    NSMutableString* EBodyuserID = [[NSMutableString alloc] init];
    for (int i = 0; i < 8; i++) {
        [EBodyuserID appendString:[NSString stringWithFormat:@"%d", arc4random_uniform(10)]];
    }
    return EBodyuserID;
}

- (NSInteger)getAge {
    return arc4random_uniform(81)+18;
}

#pragma mark - IBAction
- (IBAction)startSacn:(id)sender {
    if (self.currDeviceInfo != nil) {
        [self.currDeviceInfo disconnectDevice];
    } else {
        [self.sdk cancelAllConnect];
    }
    [self.sdk startScan];
    [self addLogWhitText:@"startScan"];
}

- (IBAction)cancelScan:(id)sender {
    [self.sdk cancelScan];
    [self addLogWhitText:@"cancelScan"];
}

- (IBAction)disconnectDevice:(id)sender {
    if (self.currDeviceInfo != nil) {
        [self.currDeviceInfo disconnectDevice];
        [self addLogWhitText:@"disconnectDevice"];
    } else {
        [self.sdk cancelAllConnect];
        [self addLogWhitText:@"cancelAllConnect"];
    }
}

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

- (IBAction)EmailAction:(id)sender {
    [self emailLog];
}

- (IBAction)refeshAction:(id)sender {
    [self clearLogStr];
    [self.sdk cancelAllConnect];
    [self.sdk startScan];
}

- (IBAction)share:(id)sender {
    [self shareLog];
}

- (IBAction)email:(id)sender {
    if ([MFMailComposeViewController canSendMail]) {
        [self emailLog];
    } else {
        [self shareLog];
    }
}

- (void)shareLog {
    NSString *logPath = kMicroLifeDeviceSDKLogZip;
    NSURL *logURL = [NSURL fileURLWithPath:logPath];
    NSMutableArray *shares = [NSMutableArray arrayWithObject:logURL];
    if (self.filePath) {
        NSURL *fileURL = [NSURL fileURLWithPath:self.filePath];
        [shares addObject:fileURL];
    }
    if (self.rowPath) {
        NSURL *rowURL = [NSURL fileURLWithPath:self.rowPath];
        [shares addObject:rowURL];
    }
    [self shareWithActivityItems:shares CallBlock:^(BOOL completed) {
        
    }];
}

- (void)emailLog {
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    NSString *appVersion = [NSString stringWithFormat:@"V%@.%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
    [[LogManager sharedInstance] sendSupportMailWith:999 Type:@"SDK" Info:@"" AppName:appName AppVersion:appVersion User:@"" Emails:@[@"willy.wu@microlife.com.tw"]];
}

#pragma mark -
- (void)setupKeyboardShowHide {
    kWeakSelf(self)
    [self.view setupKeyboardShow:^(NSNotification * _Nonnull notifacation) {
        //such as
        NSDictionary* info = [notifacation userInfo];
        //get the size of key board
        CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
        //make transform when key board show CGRect
        [weakself.view setFrame:CGRectMake(0, -kbSize.height, weakself.view.frame.size.width, weakself.view.frame.size.height)];
    } hide:^(NSNotification * _Nonnull notifacation) {
        [weakself.view setFrame:CGRectMake(0, 0, weakself.view.frame.size.width, weakself.view.frame.size.height)];
    }];
    [self.view setupForDismissKeyboard];
}

- (void)shareWithActivityItems:(NSArray *)activityItems CallBlock:(void (^)(BOOL completed))block {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
        activityVC.completionWithItemsHandler = ^(NSString *activityType,BOOL completed,NSArray *returnedItems,NSError *activityError) {
            block(completed);
        };
        [self presentViewController:activityVC animated:YES completion:nil];
    });
}

#pragma mark - DataResponseDelegate
- (void)connectDeviceInfo:(id)device PeripheralState:(CBPeripheralState)state {
    NSString *log = [NSString stringWithFormat:@"connect Device：%@ PeripheralState：",device];
    switch (state) {
        case CBPeripheralStateConnecting:
            log = [log stringByAppendingFormat:@"Connecting"];
            break;
        case CBPeripheralStateConnected:
            self.currDeviceInfo = device;
            log = [log stringByAppendingFormat:@"Connected"];
            [self file:[device name]];
            break;
        case CBPeripheralStateDisconnecting:
            log = [log stringByAppendingFormat:@"Disconnecting"];
            break;
        case CBPeripheralStateDisconnected:
            self.currDeviceInfo = nil;
            log = [log stringByAppendingFormat:@"Disconnected"];
            break;
        default:
            break;
    }
    [self addLogWhitText:log];
}

- (void)log:(id)device CMD:(NSInteger)CMD Model:(id)model Error:(NSError *)error {
    if ([model isKindOfClass:[NSDictionary class]]) {
        NSString *log = [NSString stringWithFormat:@"%@ CMD：%02lX ReadData Dictionary：%@ error：%@", device, CMD, model, error];
        [self addLogWhitText:log];
        for (NSString *key in [model allKeys] ) {
            [self log:device CMD:CMD Model:model[key] Error:error];
        }
    } else if ([model isKindOfClass:[NSData class]]) {
        MicroLifeDataModel *dataModel = [MicroLifeDataModel stringWithValue:model];
        NSString *log = [NSString stringWithFormat:@"%@ CMD：%02lX ReadData Value：%@ error：%@", device, CMD, dataModel.dataValue, error];
        [self addLogWhitText:log];
    } else {
        NSString *log = [NSString stringWithFormat:@"%@ CMD：%02lX ReadData Model：%@ UUID：%@ error：%@", device, CMD, [model parseDictionary], [model UUID], error];
        [self addLogWhitText:log];
    }
}

- (void)file:(NSString *)name {
    NSArray *arry = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    
    NSString *date = [IdeabusToolBox ib_CurrentDateWithFormat:@"yyyy-MM-dd HH:mm"];
    
    self.fileName = [NSString stringWithFormat:@"%@[Log][%@].txt",name,date];
    self.filePath = [[arry lastObject]stringByAppendingPathComponent:self.fileName];
    
    self.rowName = [NSString stringWithFormat:@"%@[Row][%@].txt",name,date];
    self.rowPath = [[arry lastObject]stringByAppendingPathComponent:self.rowName];
}

- (void)writeData:(id)stringData {
    NSString* writeStr = [NSString stringWithFormat:@"%@ ",self.date];
    if ([stringData isKindOfClass:[NSData class]]) {
        NSData *data = stringData;
        writeStr = [writeStr stringByAppendingFormat:@"length = %ld, bytes = %@\n",data.length,[data.debugDescription uppercaseString]];
    } else {
        writeStr = [writeStr stringByAppendingFormat:@"%@\n",stringData];
    }
    NSData* writeData = [writeStr dataUsingEncoding:NSUTF8StringEncoding];
    NSFileManager *fileManager  = [NSFileManager defaultManager];
    BOOL createPathOk = YES;
    if (![fileManager fileExistsAtPath:[self.filePath stringByDeletingLastPathComponent] isDirectory:&createPathOk]) {
        [fileManager createDirectoryAtPath:[self.filePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![fileManager fileExistsAtPath:self.filePath]){
        [writeData writeToFile:self.filePath atomically:NO];
    }else{
        NSFileHandle* fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.filePath];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:writeData];
        [fileHandler closeFile];
    }
}

- (void)writeRowData:(id)stringData {
    NSString* writeStr = @"";
    if ([stringData isKindOfClass:[NSData class]]) {
        NSData *data = stringData;
        writeStr = [writeStr stringByAppendingFormat:@"%@\n",[data.debugDescription uppercaseString]];
    } else {
        writeStr = [writeStr stringByAppendingFormat:@"%@\n",stringData];
    }
    NSData* writeData = [writeStr dataUsingEncoding:NSUTF8StringEncoding];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL createPathOk = YES;
    if (![fileManager fileExistsAtPath:[self.rowPath stringByDeletingLastPathComponent] isDirectory:&createPathOk]) {
        [fileManager createDirectoryAtPath:[self.rowPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (![fileManager fileExistsAtPath:self.rowPath]) {
        [writeData writeToFile:self.rowPath atomically:NO];
    } else {
        NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.rowPath];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:writeData];
        [fileHandler closeFile];
    }
}

- (void)showHIinfPressurePickView:(NSString *)selectedItem ConfirmBlock:(confirmBlock)confirmBlock CancelBlock:(cancelBlock)cancelBlock HideBlock:(hideBlock)hideBlock {
    NSMutableArray *dataSource = [NSMutableArray arrayWithObjects:@"0",@"140",@"160",@"180",@"200",@"220",@"240",@"280", nil];
    IdeabusPickView *ideabusPickView = [[IdeabusPickView alloc] initWithDataSource:dataSource selectedItem:selectedItem titleName:@"HI_infPressure" confirmButtonName:NSLocalizedString(@"Save",nil) confirmBlock:confirmBlock cancelButtonName:NSLocalizedString(@"Cancel",nil) cancelBlock:cancelBlock hideBlock:hideBlock];
    [ideabusPickView show];
}

- (void)showIntervalPickView:(NSString *)selectedItem ConfirmBlock:(confirmBlock)confirmBlock CancelBlock:(cancelBlock)cancelBlock HideBlock:(hideBlock)hideBlock {
    NSMutableArray *dataSource = [NSMutableArray arrayWithObjects:@"5",@"10",@"15",@"20",@"30",@"60", nil];
    IdeabusPickView *ideabusPickView = [[IdeabusPickView alloc] initWithDataSource:dataSource selectedItem:selectedItem titleName:@"Interval" confirmButtonName:NSLocalizedString(@"Save",nil) confirmBlock:confirmBlock cancelButtonName:NSLocalizedString(@"Cancel",nil) cancelBlock:cancelBlock hideBlock:hideBlock];
    [ideabusPickView show];
}

#pragma mark - NSUserDefaults存取類
#pragma mark 將變量存至NSUserDefaults
- (void)saveNSUserDefaults:(id)value Key:(NSString *)key {
    [IdeabusToolBox ib_SaveNSUserDefaults:value Key:key];
}

#pragma mark 從NSUserDefaults讀取變量
- (id)readNSUserDefaults:(NSString *)key {
    return [IdeabusToolBox ib_ReadNSUserDefaults:key];
}

/*
#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
