//
//  Utils.m
//  ASR033W
//
//  Created by mac on 2020/11/26.
//

#import "Utils.h"
#import "System.h"

@implementation Utils
+ (void)showAlert:(NSString*)title message:(NSString*)message {
    dispatch_async(dispatch_get_main_queue(),^{
        UIViewController *resultVC = [[UIApplication sharedApplication].keyWindow rootViewController];
        UIViewController *vc = [self findBestViewController:resultVC];
        if ([vc isKindOfClass:[UIAlertController class]]) {
            [vc dismissViewControllerAnimated:YES completion:nil];;
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:ok];
        while (resultVC.presentedViewController) {
            resultVC = resultVC.presentedViewController;
        }
        [resultVC presentViewController:alert animated:YES completion:nil];
    });
}
+ (UIViewController*)findBestViewController:(UIViewController*)vc {
    if (vc.presentedViewController) {
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.topViewController];
        else
            return vc;
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.selectedViewController];
        else
            return vc;
    } else {
        return vc;
    }
}
+ (BOOL)CheckSubscribeRFIDTopic {
    if (![[System sharedSystem] getSubscribeRFIDTopic]) {
        [self showAlert:@"" message:@"Please open RFID!"];
        return NO;
    } else {
        return YES;
    }
}
@end
@implementation NSString (NSStringHexToBytes)
-(NSData*) hexStringToBytes {
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= self.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [self substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}
@end
