//
//  AppDelegate.m
//  RedAnt ERP Suite
//
//  Created by Ray on 14-5-19.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "AppDelegate.h"
#import "UILabel+FontAppearance.h"
#import "MainViewController.h"
@implementation AppDelegate
{
#ifdef USE_SOFTSCAN
    DeviceInfo* _softScanDeviceInfo;
#endif
    DeviceInfo* _deviceInfoToTrigger;
}
@synthesize price_hidden = _price_hidden;
@synthesize ScanApi;
@synthesize ScanApiConsumer;
@synthesize scanApiVersion;
//@synthesize devices;
-(void) set_priceHidden:(bool)price_hidden
{
    _price_hidden = price_hidden;
    
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    
    //    NSObject* obj;
    //    [obj isEqual:@""];
    
    [avc showHidePrice];
}
-(void) update_count_mark
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        
        
        if(self.user==nil||self.cart_count==0)
        {
            main_vc.label_ccount.hidden = true;
            //            NSString* title = [NSString stringWithFormat:@"Sign in"];
            //            [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            //
            //            main_vc.labelMode.text=nil;
            //            [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
            //            //        [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
            //            //        main_vc.buttonUser.hidden=true;
            //            //        main_vc.buttonUser.hidden=false;
            //            //         [main_vc.headerView setNeedsDisplay];
            //            //        [main_vc.headerView setNeedsLayout];
            //            return;
        }
        else
        {
            
            NSString* strcount;
            if(self.cart_count>999)
                strcount=@"999+";
            else
                strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
            
            main_vc.label_ccount.text = strcount;
            if(strcount.length==1)
                main_vc.label_ccount.frame = CGRectMake(370, 15, 21, 21);
            if(strcount.length==2)
                main_vc.label_ccount.frame = CGRectMake(364, 15, 25, 21);
            if(strcount.length==3)
                main_vc.label_ccount.frame = CGRectMake(360, 15, 31, 21);
            if(strcount.length==4)
                main_vc.label_ccount.frame = CGRectMake(349, 15, 42, 21);
            // [main_vc.label_ccount sizeToFit];
            // main_vc.label_ccount.center = CGPointMake(360, 15);
            
            main_vc.label_ccount.hidden = false;
            
            
            //            if(self.user_type==USER_ROLE_CUSTOMER)
            //            {
            //                NSString* title = [NSString stringWithFormat:@"%@",self.user];
            //                [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            //                main_vc.labelMode.text=nil;
            //                [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
            //
            //                //            [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
            //                //            main_vc.buttonUser.hidden=true;
            //                //            main_vc.buttonUser.hidden=false;
            //                //             [main_vc.headerView setNeedsDisplay];
            //                //            [main_vc.headerView setNeedsLayout];
            //            }
            //            else
            //            {
            //                if([mode isEqualToString:@"Regualar Mode"])
            //                {
            //                    NSString* title = self.user;
            //                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            //
            //                    main_vc.labelMode.text=@"RM";
            //                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
            //                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
            //                    //                main_vc.buttonUser.hidden=true;
            //                    //                main_vc.buttonUser.hidden=false;
            //                    //                 [main_vc.headerView setNeedsDisplay];
            //                    //                [main_vc.headerView setNeedsLayout];
            //                }
            //                else
            //                {
            //                    NSString* title = self.user;
            //                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            //
            //                    main_vc.labelMode.text=@"TM";
            //                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
            //                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x009966) forState:UIControlStateNormal];
            //                    //                main_vc.buttonUser.hidden=true;
            //                    //                main_vc.buttonUser.hidden=false;
            //                    //                 [main_vc.headerView setNeedsDisplay];
            //                    //                [main_vc.headerView setNeedsLayout];
            //                }
            //
            //                NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
            //                NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
            //                if(contact==nil||contact.length==0)
            //                {
            //                    contact=@"No Name";
            //                    [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            //                }
            //                else
            //                {
            //
            //                    if(contact==nil||contact.length==0)
            //                    {
            //                        contact=@"No Name";
            //                        [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            //                    }
            //                    else
            //                    {
            //                        [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
            //                    }
            //                }
            //
            //                NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
            //                if(contact.length>0)
            //                    [arr_contact addObject:contact];
            //                if(customer.length>0)
            //                    [arr_contact addObject:customer];
            //
            //                NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
            //
            //
            //                [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
            //
            //            }
        }
    });
    
    
}
-(void) closeOrder
{
    self.order_code = nil;
    self.order_customer_id = nil;
    self.customerInfo = nil;
    self.contact_id = nil;
    [self SetMode:nil];
    //   [self SetSo:nil];
    
    
    
    [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
    [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
}
-(void) switchToPreviousVC
{
    MainViewController * main_vc= (MainViewController*)self.main_vc;
    
    [main_vc switchToPreviousVC];
}

-(void) SetMode:(NSString*)mode
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        if(self.user==nil)
        {
            
            NSString* title = [NSString stringWithFormat:@"Sign in"];
            [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            
            main_vc.labelMode.text=nil;
            [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
            //        [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
            //        main_vc.buttonUser.hidden=true;
            //        main_vc.buttonUser.hidden=false;
            //         [main_vc.headerView setNeedsDisplay];
            //        [main_vc.headerView setNeedsLayout];
            return;
        }
        else
        {
            if(self.user_type==USER_ROLE_CUSTOMER)
            {
                NSString* title = [NSString stringWithFormat:@"%@",self.user];
                [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                main_vc.labelMode.text=nil;
                [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
                
                //            [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
                //            main_vc.buttonUser.hidden=true;
                //            main_vc.buttonUser.hidden=false;
                //             [main_vc.headerView setNeedsDisplay];
                //            [main_vc.headerView setNeedsLayout];
            }
            else
            {
                if([mode isEqualToString:@"Regular Mode"])
                {
                    NSString* title = self.user;
                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                    
                    main_vc.labelMode.text=@"Regular Mode";
                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
                    //                main_vc.buttonUser.hidden=true;
                    //                main_vc.buttonUser.hidden=false;
                    //                 [main_vc.headerView setNeedsDisplay];
                    //                [main_vc.headerView setNeedsLayout];
                }
                else
                {
                    NSString* title = self.user;
                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                    
                    main_vc.labelMode.text=@"Trade Show Mode";
                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x009966) forState:UIControlStateNormal];
                    //                main_vc.buttonUser.hidden=true;
                    //                main_vc.buttonUser.hidden=false;
                    //                 [main_vc.headerView setNeedsDisplay];
                    //                [main_vc.headerView setNeedsLayout];
                }
                
                NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
                NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
                if(self.customerInfo==nil)
                {
                    //                contact=@"No Name";    if(customerinfo==nil)
                    //                {
                    contact=@"Select Contact";
                    [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                }
                else
                {
                    
                    if(contact==nil||contact.length==0)
                    {
                        contact=@"No Name";
                        [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                    }
                    else
                    {
                        [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
                    }
                }
                
                NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
                if(contact.length>0)
                    [arr_contact addObject:contact];
                if(customer.length>0)
                    [arr_contact addObject:customer];
                
                NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
                
                
                [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
                
            }
        }
    });
}


-(void) SetSo:(NSString *)So
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        if(self.user==nil)
        {
            
            //            NSString* title = [NSString stringWithFormat:@"Sign in"];
            main_vc.labelSo.text=nil;
            
            return;
        }
        else
        {
            if(self.user_type==USER_ROLE_CUSTOMER)
            {
                
                
                main_vc.labelSo.text=nil;
                //            main_vc.buttonUser.hidden=true;
                //            main_vc.buttonUser.hidden=false;
                //             [main_vc.headerView setNeedsDisplay];
                //            [main_vc.headerView setNeedsLayout];
            }
            else
            {
                if(So.length==0)
                    main_vc.labelSo.text=nil;
                else
                {
                    NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
                    main_vc.labelSo.text=text;
                }
            }
        }
    });
}
//- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
//    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
//        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
//        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
//    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
//        UINavigationController* navigationController = (UINavigationController*)rootViewController;
//        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
//    } else if (rootViewController.presentedViewController) {
//        UIViewController* presentedViewController = rootViewController.presentedViewController;
//        return [self topViewControllerWithRootViewController:presentedViewController];
//    } else {
//        return rootViewController;
//    }
//}
//- (UIViewController*)topViewController {
//    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
//}
//-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
////      // Get topmost/visible view controller
//    UIViewController *currentViewController = [self topViewController];
//
//    if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
//
//        return UIInterfaceOrientationMaskPortrait;
//    }
////
////      // Only allow portrait (standard behaviour)
//    return UIInterfaceOrientationMaskAll;
//}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    NSString* order_filter_source_path =[[NSBundle mainBundle]  pathForResource:@"status_filter_cadedate" ofType:@"json" ];
    
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
    
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
        
        NSLog(@"文件已经存在了");
        
    }
    else
    {
        
        
        
        //        NSLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
        
        NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
        
        //        NSLog(@"mainBundleFile==%@",mainBundleFile);
        
        [[NSFileManager defaultManager] createFileAtPath:dist_path
         
                                                contents:mainBundleFile
         
                                              attributes:nil];
        
    }
    
    if (! [iSalesDB initializeDb])
        // TODO: alert the user!
        DebugLog(@"couldn't init db");
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
    self.contact_id=nil;
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
    if([enable_cache isEqualToString:@"false"])
        self.bEnable_Cache = false;
    else
        self.bEnable_Cache = true;
    
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    self.build =[infoDict objectForKey:@"CFBundleVersion"];
    
    
    
    //scanner
    
    self.devices=[[NSMutableArray alloc]init];
    
    // change this to YES if you want SingleEntry to
    // confirm the decoded data
    _doAppDataConfirmation=NO;
    
    if(ScanApi==nil){
#ifdef USE_SOFTSCAN
        // this is useful for SoftScan to keep a handle
        // that is used in the trigger button
        _softScanDeviceInfo=nil;
#endif
        
        ScanApi=[[ScanApiHelper alloc]init];
        [ScanApi setDelegate:self];
        self.enable_ScannerLog = true;
        self.api_Status= API_STOP;
        
        
    }
    
    
    //UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:uialertcontroller.class, nil];
    //  [appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) Logout
{
    self.user = nil;
    self.password=nil;
    self.user_icon=nil;
    self.user_type = 0;
    self.bLogin = false;
    self.contact_id=nil;
    self.customerInfo = nil;
    self.order_code = nil;
    
    
    [self SetMode:nil];
    
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"regisger success:%@",deviceToken);
    
    //注册成功，将deviceToken保存到应用服务器数据库中
}
#pragma mark - Scaner
-(void)onTimer: (NSTimer*)theTimer{
    if(theTimer==ScanApiConsumer){
        
        //  [self addlog:@"ScanApi::doScanApiReceive:"];
        [ScanApi doScanApiReceive];
    }
}
-(void) addlog:(NSString*) newtext
{
    if(!self.enable_ScannerLog)
        return;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* date;
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        date = [formatter stringFromDate:[NSDate date]];
        
        
        if(newtext.length<=0)
            return;
        NSString* text = self.log;
        if(text.length==0)
            text=@"";
        text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
        self.log = text;
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onLogUpdate];
    });
}
- (void)enableScanner:(bool)enable {
    
    [self addlog:@"Enable scanner:"];
    
    if(enable)
    {
        [self addlog:@"Enable"];
        
        self.api_Status =  API_INIT;
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        self.Status_Text = @"Initialize...";
        [avc onStatusChanged:@"Initialize..."];
        [ScanApi open];
        [self addlog:@"ScanApi open"];
        
        ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
        [self addlog:@"ScanApiConsumer init"];
        
        //        [ScanApi close];
        //        [self addlog:@"ScanApi opent"];
    }
    else
    {
        [self addlog:@"Disable"];
        
        
        //        [ScanApiConsumer invalidate];
        //        ScanApiConsumer= nil;
        //        [self addlog:@"ScanApiConsumer invalidate"];
        
        
        self.api_Status =  API_CLOSING;
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        self.Status_Text = @"Stoping...";
        [avc onStatusChanged:@"Stoping..."];
        [ScanApi close];
        
        
        [self addlog:@"ScanApi close"];
        
        
    }
}

#pragma mark - Device Info List management
-(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
    
    [self addlog:@"updateDevicesList:"];
    
    if(add==YES){
        [self.devices addObject:deviceInfo];
    }
    else{
        [self.devices removeObject:deviceInfo];
    }
    
    NSMutableString* temp=[[NSMutableString alloc]init];
    for (DeviceInfo* info in self.devices) {
        [temp appendString:[info getName]];
        [temp appendString:@"\n"];
    }
    if(self.devices.count>0)
        [temp appendString:@"ready to scan"];
    else
        [temp appendString:@"Waiting for Scanner..."];
    
    
    // _Status.text=temp ;
    [self addlog:temp];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    self.Status_Text = temp;
    [avc onStatusChanged:temp];
    [avc OnUpdateDevicesList];
    
    // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
    // [self.dev_table reloadData];
    
}
#pragma mark - ScanApiHelper complete delegates
// THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
// TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
// IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
// CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
// THE SCANNER, THESE CALLBACKS CAN BE REMOVED

// callback received when the Get Symbology Status is completed
-(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
    [self addlog:@"onGetSymbologyDpm:"];
    
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
        if(deviceInfo!=nil){
            ISktScanSymbology* symbology=[[scanObj Property]Symbology];
            if([symbology getStatus]==kSktScanSymbologyStatusDisable){
                [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
            }
        }
    }
    else{
        // an error message should be displayed here
        // indicating that the DPM symbology status cannot be retrieved
    }
}

// callback received when the Set Symbology Status is completed
-(void)onSetSymbology:(ISktScanObject*)scanObj{
    [self addlog:@"onSetSymbology:"];
    
    SKTRESULT result=[[scanObj Msg]Result];
    if(!SKTSUCCESS(result)){
        // display an error message saying a symbology cannot be set
    }
}

/**
 *
 */
-(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
    
    [self addlog:@"onSetDataConfirmationMode:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        
        [self addlog:@"DataConfirmation Mode OK"];
        
    }
    else{
        [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
    }
}


/**
 *
 */
-(void) onDataConfirmation:(ISktScanObject*)scanObj{
    [self addlog:@"onDataConfirmation:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Data Confirmed OK"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
    [self addlog:@"onSetLocalDecodeAction:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Local Decode Action OK"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
    }
}

/**
 *
 */
-(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        ISktScanProperty* property=[scanObj Property];
        
        [self addlog:@"SoftScan status:"];
        if([property getByte]==kSktScanEnableSoftScan){
            [self addlog:@"SoftScan is ENABLED"];
            _softScannerEnabled=TRUE;
        }
        else{
            _softScannerEnabled=FALSE;
            [self addlog:@"SoftScan is DISABLED"];
        }
        
        
    }
    else{
        [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
    [self addlog:@"onSetSoftScanStatus:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"SoftScan set status success"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetTrigger:(ISktScanObject*)scanObj{
    [self addlog:@"onSetTrigger:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Trigger set success"];
    }
    else{
        
        
        [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
    [self addlog:@"onGetScanApiVersion:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result))
    {
        ISktScanProperty*property=[scanObj Property];
        if([property getType]==kSktScanPropTypeVersion)
        {
            scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
                            [[property Version]getMajor],
                            [[property Version]getMiddle],
                            [[property Version]getMinor],
                            [[property Version]getBuild]];
        }
    }
    else{
        scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
    }
    
    
    [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
}

/**
 *
 */
#ifdef USE_SOFTSCAN
-(void) onSetOverlayView:(ISktScanObject*)scanObj{
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Overlay view set success"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
        
        
    }
}
#endif
/**
 * called each time a device connects to the host
 * @param result contains the result of the connection
 * @param newDevice contains the device information
 */
-(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
    [self addlog:@"onDeviceArrival:"];
    
    [self updateDevicesList:deviceInfo Add:YES];
    
    
#ifdef USE_SOFTSCAN
    // if the scanner is a SoftScan scanner
    if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
        //  _softScannerTriggerBtn.hidden=NO;
        _softScanDeviceInfo=deviceInfo;
        if(_deviceInfoToTrigger==nil)
            _deviceInfoToTrigger=deviceInfo;
        NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
        [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
        [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
    }
    else
#endif
    {
        if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
            //            _softScannerTriggerBtn.hidden=NO;
            _deviceInfoToTrigger=deviceInfo;
        }
        if(_doAppDataConfirmation==YES){
            // switch the comment between the 2 following lines for handling the
            // data confirmation beep from the scanner (local)
            // if none is set, the scanner will beep only once when SingleEntry actually
            // confirm the decoded data, otherwise the scanner will beep twice, one locally,
            // and one when SingleEntry will confirm the decoded data
            [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
            
            //        [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
        }
        
        // for demonstration only, let's make sure the DPM is enabled
        // first interrogate the scanner to see if it's already enabled
        // and in the onGetSymbologyDpm callback, if the DPM is not already set
        // then we send a Symbology property to enable it.
        [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
    }
    
    
}


/**
 * called each time a device disconnect from the host
 * @param deviceRemoved contains the device information
 */
-(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
    
    [self addlog:@"onDeviceRemoval:"];
    [self updateDevicesList:deviceRemoved Add:NO];
    if(_deviceInfoToTrigger==deviceRemoved){
        _deviceInfoToTrigger=nil;
    }
#ifdef USE_SOFTSCAN
    if(_softScanDeviceInfo==deviceRemoved){
        _softScanDeviceInfo=nil;
    }
    if(_deviceInfoToTrigger==nil)
        _deviceInfoToTrigger=_softScanDeviceInfo;
#endif
    if(_deviceInfoToTrigger==nil){
        //        _softScannerTriggerBtn.hidden=YES;
    }
}

/**
 * called each time ScanAPI is reporting an error
 * @param result contains the error code
 */
-(void) onError:(SKTRESULT) result{
    [self addlog:@"onError:"];
    
    [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
    
    //   _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
    
}

/**
 * called each time ScanAPI receives decoded data from scanner
 * @param deviceInfo contains the device information from which
 * the data has been decoded
 * @param decodedData contains the decoded data information
 */
-(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    
    [self addlog:@"onDecodedDataResult:"];
    //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    if(SKTSUCCESS(result)){
        
        
        NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onDecodedData:cleanString];
        //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
        [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
        if(_doAppDataConfirmation==YES){
            [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
        }
    }
}

-(void) test_onDecodedDataResult:(NSString*) value
{
    
    [self addlog:@"onDecodedDataResult:"];
    //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    if(true){
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onDecodedData:value];
        //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
        [self addlog:value];
        //        if(_doAppDataConfirmation==YES){
        //            [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
        //        }
    }
}
-(void) didRotated
{
    
}


/**
 * called when ScanAPI initialization has been completed
 * @param result contains the initialization result
 */
-(void) onScanApiInitializeComplete:(SKTRESULT) result{
    
    [self addlog:@"onScanApiInitializeComplete:"];
    
    if(SKTSUCCESS(result))
    {
        self.api_Status =  API_START;
        
        NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
        [self addlog:strlog];
        
#ifdef USE_SOFTSCAN
        // make sure we support SoftScan
        [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
        
        // check if SoftScan is enabled
        [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
#else
        // disable support SoftScan (Default, not really needed if it was never activated)
        [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
#endif
        
        // ask for ScanAPI version (not a requirement but always nice to know)
        [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
        
        // configure ScanAPI for doing App Data confirmation,
        // if TRUE then SingleEntry will confirm the decoded data
        if(_doAppDataConfirmation==YES){
            [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
        }
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onStatusChanged:@"Waiting for scanner..."];
        self.Status_Text = @"Waiting for scanner...";
        //   _Status.text=@"Waiting for scanner...";
    }
    else{
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
        self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        [self addlog:strlog];
    }
}

/**
 * called when ScanAPI has been terminated. This will be
 * the last message received from ScanAPI
 */
-(void) onScanApiTerminated{
    
    [self addlog:@"onScanApiTerminated:"];
    
    
    [ScanApiConsumer invalidate];
    ScanApiConsumer= nil;
    [self addlog:@"ScanApiConsumer invalidate"];
    
    self.api_Status =  API_STOP;
    
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onStatusChanged:@"Off"];
    self.Status_Text =@"Off";
    //   _Status.text = @"Off";
    
}

/**
 * called when an error occurs during the retrieval
 * of a ScanObject from ScanAPI.
 * @param result contains the retrieval error code
 */
-(void) onErrorRetrievingScanObject:(SKTRESULT) result{
    
    [self addlog:@"onErrorRetrievingScanObject:"];
    [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
    //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
}


@end
