#import "AppDelegate.h"
#import "UserData.h"
#import "SystemSetting.h"
#import "DatabaseManeger.h"
@interface AppDelegate ()
@property (readwrite, nonatomic) SelectFlag backupUseMask;
@property (strong, nonatomic) NSMutableArray *backupSelectMasks;
@end

@implementation AppDelegate{
    SystemSetting * systemSetting;
    UIAlertView *errorAlert;
}

@synthesize mReader,mAsReaderGUN;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.insertOperation = [[NSOperationQueue alloc] init];
    systemSetting = [SystemSetting sharedSystemSetting];
    if (![systemSetting getNotFirstUsed]) {
        [systemSetting setTidOn:NO];
        [systemSetting setTidLength:4];
        [systemSetting setNotFirstUsed:YES];
        [systemSetting setBuzzer:Buzzer_High];
        [systemSetting setVibrator:Vibrator_On];
        [systemSetting setInventoryTime:400];
        [systemSetting setIdleTime:100];
        [systemSetting setAutoOffTime:600];
        [systemSetting setQValue:4];
        [systemSetting setAlgorithm:DynamicQ];
        [systemSetting setMaxQ:15];
        [systemSetting setMinQ:0];
        [systemSetting setSleepTime:300];
        [systemSetting setMaskTypeValue:MaskType_NO_MASK];
        [systemSetting setLinkProfileValue:3];
        [systemSetting setDefaultLinkProfileValue:1];
        [systemSetting setOperationTime:0];
        [systemSetting setPowerGain:300];
        [systemSetting setInventorySession:Session_S0];
        [systemSetting setSessionFlag:SessionFlag_AB];
        [systemSetting setContinuousMode:YES];
        [systemSetting setRssiMode:NO];
        [systemSetting setPropBarcodeMode:YES];
        [systemSetting setEpcMaskMatchMode:NO];
        [systemSetting setDisPlayPC:YES];
        [systemSetting setLbtItemData:nil];
        [systemSetting setEpcMaskData:nil];
        [systemSetting setUseSelectionMask:SelectFlag_All];
        [systemSetting setSelectionEpcMaskData:nil];;
        [systemSetting setBarcodeParamData:nil];
        [systemSetting setBuzzerTime:1];
        [systemSetting setVibratorTime:1];
        [systemSetting setBarcodeReScanTime:0];
        [systemSetting setCustomPrefixSuffix:NO];
    }
    /*Robin*/
    [self redirectConsoleLogToDocumentFolder:@"logs.txt"];
    [AsRingDeviceSDK sharedAsRingDeviceSDK];
    [self removeLogFile];
    [self redirectNSLogToDocumentFolder];
    //For Debugging Alert
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(showAlert:) name:@"Alert" object:nil];
    /*End Robin*/
    return YES;
}


/*Robin*/
- (void)showAlert:(NSNotification *)notification {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *data = [[notification userInfo] objectForKey:@"DATA"];
        if(errorAlert == nil)
        errorAlert
        = [[UIAlertView alloc] initWithTitle:@"Alert"
                                     message:data
                                    delegate:self
                           cancelButtonTitle:NSLocalizedString(@"OK", @"")
                           otherButtonTitles:nil];
       
        [errorAlert setMessage:data];
        
        
        if([errorAlert isVisible])
            return;
        
        [errorAlert show];
        
    });
}
 


- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}
#pragma mark - Blaster Method
- (void)initMask:(NSString *)maskValue maskType:(MaskType)maskType {
    if (maskValue != nil) {
        if (maskType == MaskType_Selection) {
            self.backupUseMask = [self.mReader useSelectionMask];
            
            for (int i=MIN_SELECTION_MASK; i < MAX_SELECTION_MASK; i++) {
                if (![self.mReader usedSelectionMask:i]) {
                    break;
                }
                
                AsSelectMaskParam *param = [self.mReader getSelectionMask:i];
                
                [self.backupSelectMasks addObject:param];
            }
        }
        
        AsSelectMaskParam *param = [[AsSelectMaskParam alloc] initWithParameterIndex:0 target:MaskTarget_SL action:MaskAction_AB bank:Bank_EPC offset:32 mask:[maskValue substringFromIndex:4] used:YES];
        [self.mReader setSelectionMask:0 withParam:param];
        [self.mReader setUseSelectionMask:SelectFlag_SL];
        
        for (int i=1; i < MAX_SELECTION_MASK; i++) {
            [self.mReader setMaskUsed:i used:NO];
        }
    }
}

- (void)exitMask {
    [self.mReader setUseSelectionMask:self.backupUseMask];
    
    for (int i=MIN_SELECTION_MASK; i < MAX_SELECTION_MASK; i++) {
        NSLog(@"count : %lu", (unsigned long)self.backupSelectMasks.count);
        if (self.backupSelectMasks.count < i + 1) {
            [self.mReader removeSelectionMask:i];
            break;
        }
        
        AsSelectMaskParam *param = [self.backupSelectMasks objectAtIndex:i];
        
        if (param == nil) {
            break;
        }
        
        [self.mReader setSelectionMask:i withParam:param];
    }
    
    [self.backupSelectMasks removeAllObjects];
    
    //EPC MASK Rollback
    if(self.mReader.maskTypeValue == MaskType_EPC){
        [self rollBackEpcMask];
    }
}




//robin
-(void)rollBackEpcMask
{
    int count = [self.mReader epcMaskCount];
    NSLog(@" EPC MASK Count : %d",count);
    AsSelectMaskEPCParam *param;
    NSMutableArray * maskData = [[NSMutableArray alloc] init];
    for (int i=0; i<count; i++) {
        param = [self.mReader getEpcMask:i];
        if(param !=nil)
            [maskData addObject:param];
    }
    
    [self.mReader clearEpcMask];
   
    for (AsSelectMaskEPCParam *mask in maskData) {
        [self.mReader addEpcMask:mask];
    }
    
    if (self.mReader.epcMaskMatchMode) {
        [self.mReader setEpcMaskMatchMode:YES];
    } else {
        [self.mReader setEpcMaskMatchMode:NO];
    }
    count = [self.mReader epcMaskCount];
    NSLog(@" EPC MASK Count : %d",count);
}



#pragma mark - Utility Methods
         - (NSString *)getAppVersion {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *majorVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *minorVersion = [infoDictionary objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"Version %@ Build %@", majorVersion, minorVersion];
}

-(UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    return result;
}
+ (MBProgressHUD *)showGlobalProgressHUDWithTitle:(NSString *)title {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[result view] animated:YES];
    hud.labelText = title;
    return hud;
}
+ (void)dismissGlobalHUD {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    [MBProgressHUD hideHUDForView:[result view]  animated:YES];
}

- (NSMutableArray *)backupSelectMasks {
    if (_backupSelectMasks == nil) {
        _backupSelectMasks = [[NSMutableArray alloc] init];
    }
    return _backupSelectMasks;
}


- (void)redirectNSLogToDocumentFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.txt",@"writelog"];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

- (void) removeLogFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName =[NSString stringWithFormat:@"%@.txt",@"writelog"];
    NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    float logSize = 0;
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:logFilePath]){
        logSize = [[manager attributesOfItemAtPath:logFilePath error:nil] fileSize]/(1024.0*1024);
    }
    if (logSize >= 1 ) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:logFilePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:logFilePath error:nil];
        }
    }
}
- (void) redirectConsoleLogToDocumentFolder:(NSString*)filename
{
    NSArray *paths
    = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory,
     NSUserDomainMask, YES);
    
    NSString *documentsDirectory
    = [paths objectAtIndex:0];
    
    NSString *logPath
    = [documentsDirectory stringByAppendingPathComponent:filename];
    
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding], "w",stderr);
}
@end
