#import "FirebasePlugin.h"
#import <Cordova/CDV.h>
#import "AppDelegate.h"
#import "Firebase.h"
#import "XMLConverter.h"
#import "InternetConnection.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
@import FirebaseInstanceID;
@import FirebaseMessaging;
@import FirebaseAnalytics;
@import FirebaseRemoteConfig;
@import FirebasePerformance;
@import FirebaseAuth;

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif

#ifndef NSFoundationVersionNumber_iOS_9_x_Max
#define NSFoundationVersionNumber_iOS_9_x_Max 1299
#endif

@implementation FirebasePlugin

@synthesize btnGallery;
@synthesize indicator = _indicator;
@synthesize overlay = _overlay;
@synthesize notificationCallbackId;
@synthesize tokenRefreshCallbackId;
@synthesize notificationStack;
@synthesize traces;

static NSInteger const kNotificationStackSize = 10;
static FirebasePlugin *firebasePlugin;

+ (FirebasePlugin *) firebasePlugin {
    return firebasePlugin;
}

- (void)pluginInitialize {
    NSLog(@"Starting Firebase plugin");
    firebasePlugin = self;
}


- (void)getId:(CDVInvokedUrlCommand *)command {
    __block CDVPluginResult *pluginResult;

    FIRInstanceIDHandler handler = ^(NSString *_Nullable instID, NSError *_Nullable error) {
        if (error) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:instID];
        }

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    };

    [[FIRInstanceID instanceID] getIDWithHandler:handler];
}

// DEPRECATED - alias of getToken
- (void)getInstanceId:(CDVInvokedUrlCommand *)command {
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[FIRInstanceID instanceID] token]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)getToken:(CDVInvokedUrlCommand *)command {
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[FIRInstanceID instanceID] token]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)hasPermission:(CDVInvokedUrlCommand *)command {
    BOOL enabled = NO;
    UIApplication *application = [UIApplication sharedApplication];

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        enabled = application.currentUserNotificationSettings.types != UIUserNotificationTypeNone;
    } else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
        enabled = application.enabledRemoteNotificationTypes != UIRemoteNotificationTypeNone;
#pragma GCC diagnostic pop
    }

    NSMutableDictionary* message = [NSMutableDictionary dictionaryWithCapacity:1];
    [message setObject:[NSNumber numberWithBool:enabled] forKey:@"isEnabled"];
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}

- (void)grantPermission:(CDVInvokedUrlCommand *)command {
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType notificationTypes =
            (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        } else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
#pragma GCC diagnostic pop
        }

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

        return;
    }


#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
        requestAuthorizationWithOptions:authOptions
                      completionHandler:^(BOOL granted, NSError * _Nullable error) {

            if (![NSThread isMainThread]) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [[FIRMessaging messaging] setDelegate:self];
                    [[UIApplication sharedApplication] registerForRemoteNotifications];

                    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus: granted ? CDVCommandStatus_OK : CDVCommandStatus_ERROR];
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                });
            } else {
                [[FIRMessaging messaging] setDelegate:self];
                [[UIApplication sharedApplication] registerForRemoteNotifications];
                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            }
        }
    ];
#else
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
#endif

    return;
}

- (void)verifyPhoneNumber:(CDVInvokedUrlCommand *)command {
    [self getVerificationID:command];
}

- (void)getVerificationID:(CDVInvokedUrlCommand *)command {
    NSString* number = [command.arguments objectAtIndex:0];

    [[FIRPhoneAuthProvider provider]
    verifyPhoneNumber:number
           UIDelegate:nil
           completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) {

    NSDictionary *message;

    if (error) {
        // Verification code not sent.
        message = @{
            @"code": [NSNumber numberWithInteger:error.code],
            @"description": error.description == nil ? [NSNull null] : error.description
        };

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:message];

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    } else {
        // Successful.
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:verificationID];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
  }];
}

- (void)setBadgeNumber:(CDVInvokedUrlCommand *)command {
    int number = [[command.arguments objectAtIndex:0] intValue];

    [self.commandDelegate runInBackground:^{
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)getBadgeNumber:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        long badge = [[UIApplication sharedApplication] applicationIconBadgeNumber];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:badge];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)subscribe:(CDVInvokedUrlCommand *)command {
    NSString* topic = [NSString stringWithFormat:@"/topics/%@", [command.arguments objectAtIndex:0]];

    [[FIRMessaging messaging] subscribeToTopic: topic];

    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)unsubscribe:(CDVInvokedUrlCommand *)command {
    NSString* topic = [NSString stringWithFormat:@"/topics/%@", [command.arguments objectAtIndex:0]];

    [[FIRMessaging messaging] unsubscribeFromTopic: topic];

    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)unregister:(CDVInvokedUrlCommand *)command {
    [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) {
        if (error) {
            NSLog(@"Unable to delete instance");
        } else {
            CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }
    }];
}

- (void)onNotificationOpen:(CDVInvokedUrlCommand *)command {
    self.notificationCallbackId = command.callbackId;

    if (self.notificationStack != nil && [self.notificationStack count]) {
        for (NSDictionary *userInfo in self.notificationStack) {
            [self sendNotification:userInfo];
        }
        [self.notificationStack removeAllObjects];
    }
}

- (void)onTokenRefresh:(CDVInvokedUrlCommand *)command {
    self.tokenRefreshCallbackId = command.callbackId;
    NSString* currentToken = [[FIRInstanceID instanceID] token];

    if (currentToken != nil) {
        [self sendToken:currentToken];
    }
}

- (void)sendNotification:(NSDictionary *)userInfo {
    if (self.notificationCallbackId != nil) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo];
        [pluginResult setKeepCallbackAsBool:YES];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:self.notificationCallbackId];
    } else {
        if (!self.notificationStack) {
            self.notificationStack = [[NSMutableArray alloc] init];
        }

        // stack notifications until a callback has been registered
        [self.notificationStack addObject:userInfo];

        if ([self.notificationStack count] >= kNotificationStackSize) {
            [self.notificationStack removeLastObject];
        }
    }
}

- (void)sendToken:(NSString *)token {
    if (self.tokenRefreshCallbackId != nil) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token];
        [pluginResult setKeepCallbackAsBool:YES];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:self.tokenRefreshCallbackId];
    }
}

- (void)logEvent:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* name = [command.arguments objectAtIndex:0];
        NSDictionary *parameters;
        @try {
            NSString *description = NSLocalizedString([command argumentAtIndex:1 withDefault:@"No Message Provided"], nil);
            parameters = @{ NSLocalizedDescriptionKey: description };
        }
        @catch (NSException *execption) {
            parameters = [command argumentAtIndex:1];
        }

        [FIRAnalytics logEventWithName:name parameters:parameters];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)logError:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* errorMessage = [command.arguments objectAtIndex:0];
        CLSNSLog(@"%@", errorMessage);
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)setCrashlyticsUserId:(CDVInvokedUrlCommand *)command {
    NSString* userId = [command.arguments objectAtIndex:0];

    [CrashlyticsKit setUserIdentifier:userId];
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)setScreenName:(CDVInvokedUrlCommand *)command {
    NSString* name = [command.arguments objectAtIndex:0];

    [FIRAnalytics setScreenName:name screenClass:NULL];
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)setUserId:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* id = [command.arguments objectAtIndex:0];

        [FIRAnalytics setUserID:id];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)setUserProperty:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* name = [command.arguments objectAtIndex:0];
        NSString* value = [command.arguments objectAtIndex:1];

        [FIRAnalytics setUserPropertyString:value forName:name];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)fetch:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
          FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig];

          if ([command.arguments count] > 0) {
              int expirationDuration = [[command.arguments objectAtIndex:0] intValue];

              [remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) {
                  CDVPluginResult *pluginResult;
                  if (status == FIRRemoteConfigFetchStatusSuccess) {
                      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                  } else {
                      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                  }
                  [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
              }];
          } else {
              [remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) {
                  CDVPluginResult *pluginResult;
                  if (status == FIRRemoteConfigFetchStatusSuccess) {
                      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                  } else {
                      pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                  }
                  [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
              }];
          }
    }];
}

- (void)activateFetched:(CDVInvokedUrlCommand *)command {
     [self.commandDelegate runInBackground:^{
        FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig];
         BOOL activated = [remoteConfig activateFetched];
         CDVPluginResult *pluginResult;

         if (activated) {
             pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
         } else {
             pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
         }

         [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
     }];
}

- (void)getValue:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* key = [command.arguments objectAtIndex:0];
        FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig];
        NSString* value = remoteConfig[key].stringValue;
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:value];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

//
// Performace
//
- (void)startTrace:(CDVInvokedUrlCommand *)command {

    [self.commandDelegate runInBackground:^{
        NSString* traceName = [command.arguments objectAtIndex:0];
        FIRTrace *trace = [self.traces objectForKey:traceName];

        if ( self.traces == nil) {
            self.traces = [NSMutableDictionary new];
        }

        if (trace == nil) {
            trace = [FIRPerformance startTraceWithName:traceName];
            [self.traces setObject:trace forKey:traceName ];

        }

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }];
}

- (void)incrementCounter:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* traceName = [command.arguments objectAtIndex:0];
        NSString* counterNamed = [command.arguments objectAtIndex:1];
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        FIRTrace *trace = (FIRTrace*)[self.traces objectForKey:traceName];

        if (trace != nil) {
            [trace incrementCounterNamed:counterNamed];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"];
        }

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

    }];
}

- (void)stopTrace:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        NSString* traceName = [command.arguments objectAtIndex:0];
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        FIRTrace *trace = [self.traces objectForKey:traceName];

        if (trace != nil) {
            [trace stop];
            [self.traces removeObjectForKey:traceName];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"];
        }

        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)setAnalyticsCollectionEnabled:(CDVInvokedUrlCommand *)command {
     [self.commandDelegate runInBackground:^{
        BOOL enabled = [[command argumentAtIndex:0] boolValue];

        [[FIRAnalyticsConfiguration sharedInstance] setAnalyticsCollectionEnabled:enabled];
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
     }];
}

- (void)setPerformanceCollectionEnabled:(CDVInvokedUrlCommand *)command {
     [self.commandDelegate runInBackground:^{
         BOOL enabled = [[command argumentAtIndex:0] boolValue];

         [[FIRPerformance sharedInstance] setDataCollectionEnabled:enabled];

         CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];

         [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
     }];
}

- (void)clearAllNotifications:(CDVInvokedUrlCommand *)command {
	[self.commandDelegate runInBackground:^{
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

-(NSString *)getAppRootFolderPath {
    NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * rootFolderPath = [NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]];
    NSError * error;
    NSString * myAccountsContents = [NSString stringWithContentsOfFile:rootFolderPath encoding:NSUTF8StringEncoding error:&error];
    NSData * myAccountsData = [myAccountsContents dataUsingEncoding:NSUTF8StringEncoding];
    NSArray * myAccountsArray = [NSJSONSerialization JSONObjectWithData:myAccountsData options: NSJSONReadingMutableContainers error: &error];
    NSArray * filtered = [myAccountsArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"client_id LIKE[cd] %@", @"cjakson"]];
    NSString * client_id = [filtered[0] valueForKey:@"client_id"];
    NSString * country_code = [filtered[0] valueForKey:@"country_code"];
    NSString * finalRootPath = [NSString stringWithFormat:@"%@/%@/%@/%@", directory, [self GetAppName], client_id, country_code];
    return finalRootPath;
}
-(void)GetPermissions:(CDVInvokedUrlCommand*)command {
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void)CaptureFromCamera:(CDVInvokedUrlCommand*)command {
    liveCamera= [[UIImagePickerController alloc] init];
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return;
    }
    liveCamera.delegate = self;
    liveCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
    UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
        [top presentViewController:liveCamera animated:YES completion: nil];
        self.callbackIdForImagePicker = command.callbackId;
    } else {
        popover=[[UIPopoverController alloc]initWithContentViewController:liveCamera];
        CGRect myFrame = [top.view frame];
        [popover presentPopoverFromRect:myFrame inView:top.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
}

- (void)CaptureImageFromCamera:(CDVInvokedUrlCommand*)command {
    cameraOpen= [[UIImagePickerController alloc] init];
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return;
    }
    cameraOpen.delegate = self;
    cameraOpen.sourceType = UIImagePickerControllerSourceTypeCamera;
    UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
        [top presentViewController:cameraOpen animated:YES completion: nil];
        self.callbackIdForImagePicker = command.callbackId;
    } else {
        popover=[[UIPopoverController alloc]initWithContentViewController:cameraOpen];
        CGRect myFrame = [top.view frame];
        [popover presentPopoverFromRect:myFrame inView:top.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
}

- (void)PickImageFromGallery:(CDVInvokedUrlCommand*)command {
    imagePicker= [[UIImagePickerController alloc] init];
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return;
    }
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
    if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
        [top presentViewController:imagePicker animated:YES completion: nil];
        self.callbackIdForImagePicker = command.callbackId;
    } else {
        popover=[[UIPopoverController alloc]initWithContentViewController:imagePicker];
        CGRect myFrame = [top.view frame];
        [popover presentPopoverFromRect:myFrame inView:top.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
}

-(void)RemoveFilesFromDirectory {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *imageDir = [NSString stringWithFormat:@"%@/%@/images", directory, [self GetAppName]];
    NSError *error = nil;
    if([fileManager fileExistsAtPath:imageDir]) {
        NSArray *imageFilesArr = [fileManager contentsOfDirectoryAtPath:imageDir error:&error];
        NSMutableArray *imageFilesMutArr = [imageFilesArr mutableCopy];
        if([imageFilesMutArr containsObject:@".DS_Store"]) {
            [imageFilesMutArr removeObject:@".DS_Store"];
        }
        for( int index = 0; index < [imageFilesMutArr count]; index++ ) {
            NSString *currentFile = [NSString stringWithFormat:@"%@/%@", imageDir, imageFilesMutArr[index]];
            [fileManager removeItemAtPath:currentFile error:nil];
        }
    }
}

#pragma mark - MapViewDelegate
- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
}
// Error while updating location
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    
}

- (void)StartService:(CDVInvokedUrlCommand*)command
{
    @try {
        self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
        [self.locationManager setHeadingFilter:kCLHeadingFilterNone];
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager requestWhenInUseAuthorization];
        // Allow background Update
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
            _locationManager.allowsBackgroundLocationUpdates = YES;
        }
        [self.locationManager startUpdatingLocation];
        [self KillTimers];
        self.QueueTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                                           target:self
                                                         selector:@selector(DespatchQueueNew)
                                                         userInfo:nil
                                                          repeats:YES];
        self.LocationTimer = [NSTimer scheduledTimerWithTimeInterval:30.0
                                                              target:self
                                                            selector:@selector(SendLocation)
                                                            userInfo:nil
                                                             repeats:YES];
        self.timeReaderTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
                                                                target:self
                                                              selector:@selector(timeReader)
                                                              userInfo:nil
                                                               repeats:YES];
        self.CheckSumTimer = [NSTimer scheduledTimerWithTimeInterval:180.0
                                                              target:self
                                                            selector:@selector(CheckSumIndicatorResult)
                                                            userInfo:nil
                                                             repeats:YES];
        self.authTimer = [NSTimer scheduledTimerWithTimeInterval:300.0
                                                          target:self
                                                        selector:@selector(AuthenticationRefresh)
                                                        userInfo:nil
                                                         repeats:YES];
        self.QueueToServerTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                                                   target:self
                                                                 selector:@selector(DespatchQueueMoveToServer)
                                                                 userInfo:nil
                                                                  repeats:YES];
    } @catch (NSException *exception) {
        NSLog(@"Exception is : %@", exception.description);
    }
}

- (void)KillTimers {
    if([self.QueueTimer isValid]) {
        [self.QueueTimer invalidate];
    }
    if([self.LocationTimer isValid]) {
        [self.LocationTimer invalidate];
    }
    if([self.timeReaderTimer isValid]) {
        [self.timeReaderTimer invalidate];
    }
    if([self.CheckSumTimer isValid]) {
        [self.CheckSumTimer invalidate];
    }
    if([self.QueueToServerTimer isValid]) {
        [self.QueueToServerTimer invalidate];
    }
}

- (void)QueueProcessor:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        NSString *breakIndication = @"false";
        NSString *statusIndication = @"false";
        CDVPluginResult *result = nil;
        NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *myAccountsArray = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]] encoding:NSUTF8StringEncoding error:&error] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error];
        InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
        NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
        if(networkStatus != NotReachable) {
            for( int index = 0; index < [myAccountsArray count]; index++ ) {
                NSString *clientId = [myAccountsArray[index] valueForKey:@"client_id"];
                NSString *countryCode = [myAccountsArray[index] valueForKey:@"country_code"];
                NSString *clientUrl = [myAccountsArray[index] valueForKey:@"client_url"];
                NSString *userID = [myAccountsArray[index] valueForKey:@"user_id"];
                NSString *attachFolderPath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/attachments", directory, [self GetAppName], clientId, countryCode];
                NSString *queueFolderPath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/queue", directory, [self GetAppName], clientId, countryCode];
                NSArray *attachedFilesArr = [fileManager contentsOfDirectoryAtPath:attachFolderPath error:&error];
                NSMutableArray *attachedFilesMutArr = [attachedFilesArr mutableCopy];
                if([attachedFilesMutArr containsObject:@".DS_Store"]) {
                    [attachedFilesMutArr removeObject:@".DS_Store"];
                }
                NSString *databasePath = [NSString stringWithFormat:@"%@/%@/%@/%@/database", directory, [self GetAppName], clientId, countryCode];
                if([fileManager fileExistsAtPath:databasePath]) {
                    for( int attachIndex = 0; attachIndex < [attachedFilesMutArr count]; attachIndex++ ) {
                        NSString * attachedFilesPath = [NSString stringWithFormat:@"%@/%@", attachFolderPath, attachedFilesMutArr[attachIndex]];
                        NSString *attachURL = [NSString stringWithFormat:@"%@/common/components/QueueManager/QueueUpload.aspx?file_path=attachments&client_id=%@&country_code=%@&user_id=%@&file_name=%@", clientUrl, clientId, countryCode, userID, attachedFilesMutArr[attachIndex]];
                        statusIndication = [self sendFilesToServer:attachedFilesPath fileName:attachedFilesMutArr[attachIndex] requestURL:attachURL];
                        if ([statusIndication isEqualToString:@"true"]) {
                            breakIndication = @"true";
                            break;
                        }
                    }
                    if ([statusIndication isEqualToString:@"false"]) {
                        NSArray *queueFilesArr = [fileManager contentsOfDirectoryAtPath:queueFolderPath error:&error];
                        NSMutableArray *queueFilesMutArr = [queueFilesArr mutableCopy];
                        if([queueFilesMutArr containsObject:@".DS_Store"]) {
                            [queueFilesMutArr removeObject:@".DS_Store"];
                        }
                        for( int queueIndex = 0; queueIndex < [queueFilesMutArr count]; queueIndex++ ) {
                            NSString *queueFilesPath = [NSString stringWithFormat:@"%@/%@", queueFolderPath, queueFilesMutArr[queueIndex]];
                            NSString *queueURL = [NSString stringWithFormat:@"%@/common/components/QueueManager/QueueUpload.aspx?file_path=queue&client_id=%@&country_code=%@&user_id=%@&file_name=%@", clientUrl, clientId, countryCode, userID, queueFilesMutArr[queueIndex]];
                            [self sendFilesToServer:queueFilesPath fileName:queueFilesMutArr[queueIndex] requestURL:queueURL];
                        }
                    }
                } else {
                    NSLog(@"No database directory found at the path..");
                }
                if ([breakIndication isEqualToString:@"false"]) {
                    result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
                } else {
                    result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
                }
            }
        } else {
            NSLog(@"No Internet connection..");
        }
    }];
}

-(void)DespatchQueueMoveToServer {
    [self.commandDelegate runInBackground:^{
        NSString *statusIndication = @"false";
        NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *myAccountsArray = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]] encoding:NSUTF8StringEncoding error:&error] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error];
        InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
        NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
        if(networkStatus != NotReachable) {
            for( int index = 0; index < [myAccountsArray count]; index++ ) {
                NSString *clientId = [myAccountsArray[index] valueForKey:@"client_id"];
                NSString *countryCode = [myAccountsArray[index] valueForKey:@"country_code"];
                NSString *clientUrl = [myAccountsArray[index] valueForKey:@"client_url"];
                NSString *userID = [myAccountsArray[index] valueForKey:@"user_id"];
                NSString *attachFolderPath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/attachments", directory, [self GetAppName], clientId, countryCode];
                NSString *queueFolderPath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/queue", directory, [self GetAppName], clientId, countryCode];
                NSArray *attachedFilesArr = [fileManager contentsOfDirectoryAtPath:attachFolderPath error:&error];
                NSMutableArray *attachedFilesMutArr = [attachedFilesArr mutableCopy];
                if([attachedFilesMutArr containsObject:@".DS_Store"]) {
                    [attachedFilesMutArr removeObject:@".DS_Store"];
                }
                NSString *databasePath = [NSString stringWithFormat:@"%@/%@/%@/%@/database", directory, [self GetAppName], clientId, countryCode];
                if([fileManager fileExistsAtPath:databasePath]) {
                    for( int attachIndex = 0; attachIndex < [attachedFilesMutArr count]; attachIndex++ ) {
                        NSString * attachedFilesPath = [NSString stringWithFormat:@"%@/%@", attachFolderPath, attachedFilesMutArr[attachIndex]];
                        NSString *attachURL = [NSString stringWithFormat:@"%@/common/components/QueueManager/QueueUpload.aspx?file_path=attachments&client_id=%@&country_code=%@&user_id=%@&file_name=%@", clientUrl, clientId, countryCode, userID, attachedFilesMutArr[attachIndex]];
                        statusIndication = [self sendFilesToServer:attachedFilesPath fileName:attachedFilesMutArr[attachIndex] requestURL:attachURL];
                        if ([statusIndication isEqualToString:@"true"]) {
                            break;
                        }
                    }
                    if ([statusIndication isEqualToString:@"false"]) {
                        NSArray *queueFilesArr = [fileManager contentsOfDirectoryAtPath:queueFolderPath error:&error];
                        NSMutableArray *queueFilesMutArr = [queueFilesArr mutableCopy];
                        if([queueFilesMutArr containsObject:@".DS_Store"]) {
                            [queueFilesMutArr removeObject:@".DS_Store"];
                        }
                        for( int queueIndex = 0; queueIndex < [queueFilesMutArr count]; queueIndex++ ) {
                            NSString *queueFilesPath = [NSString stringWithFormat:@"%@/%@", queueFolderPath, queueFilesMutArr[queueIndex]];
                            NSString *queueURL = [NSString stringWithFormat:@"%@/common/components/QueueManager/QueueUpload.aspx?file_path=queue&client_id=%@&country_code=%@&user_id=%@&file_name=%@", clientUrl, clientId, countryCode, userID, queueFilesMutArr[queueIndex]];
                            [self sendFilesToServer:queueFilesPath fileName:queueFilesMutArr[queueIndex] requestURL:queueURL];
                        }
                    }
                } else {
                    NSLog(@"No database directory found at the path..");
                }
            }
        } else {
            NSLog(@"No Internet connection..");
        }
    }];
}

- (NSString *)sendFilesToServer:(NSString *)filePath fileName:(NSString *)fileName requestURL:(NSString *) requestURL {
    NSString *statusIndication = @"false";
    @try {
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSError *jsonError;
            NSString *urlString =[NSString stringWithFormat:@"%@", requestURL];
            NSURL *url=[NSURL URLWithString:[[NSString stringWithFormat:@"%@", urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSMutableURLRequest *fileRequest = [[NSMutableURLRequest alloc] init];
            [fileRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [fileRequest setHTTPShouldHandleCookies:NO];
            [fileRequest setTimeoutInterval:240];
            [fileRequest setHTTPMethod:@"POST"];
            NSString *boundary = @"---------------------------14737809831466499882746641449";
            NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
            [fileRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
            NSString *fileExtension = [[filePath pathExtension] lowercaseString];
            //UIImage *yourImage= [UIImage imageNamed:filePath];
            //NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);
            NSData *imageData = [NSData dataWithContentsOfFile:filePath];
            NSMutableData *body = [NSMutableData data];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            if (imageData)
                [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"",fileName,@"\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            NSString *imgMimeType = [NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self contentTypeForImageData:fileExtension]];
            [body appendData:[imgMimeType dataUsingEncoding:NSUTF8StringEncoding]];
            if (imageData)
                [body appendData:[NSData dataWithData:imageData]];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [fileRequest setHTTPBody:body];
            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
            [fileRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [fileRequest setURL:url];
            NSURLResponse *response = nil;
            //[NSURLConnection connectionWithRequest:fileRequest delegate:self];
            NSData *responseData = [NSURLConnection sendSynchronousRequest:fileRequest returningResponse:&response error:&jsonError];
            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            NSString *returnedIndication = responseString;
            if([returnedIndication isEqualToString:@"true"]) {
                [fileManager removeItemAtPath:filePath error:&jsonError];
            } else {
                statusIndication = @"true";
            }
        } else {
            NSLog(@"Failed while sending the server");
        }
    } @catch (NSException *exception) {
        NSLog(@"Exception handled for http failure...");
        statusIndication = @"true";
    }
    return statusIndication;
}

-(void) AuthenticationRefresh {
    @try {
        InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
        NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
        if(networkStatus != NotReachable) {
            NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *rootFolderPath = [NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]];
            NSError *error;
            NSString *myAccountsContents = [NSString stringWithContentsOfFile:rootFolderPath encoding:NSUTF8StringEncoding error:&error];
            NSData *myAccountsData = [myAccountsContents dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *myAccountsArray = [NSJSONSerialization JSONObjectWithData:myAccountsData options: NSJSONReadingMutableContainers error: &error];
            for(int index = 0; index < [myAccountsArray count]; index++) {
                NSString *clientId = [myAccountsArray[index] valueForKey:@"client_id"];
                NSString *countryCode = [myAccountsArray[index] valueForKey:@"country_code"];
                NSString *userId = [myAccountsArray[index] valueForKey:@"user_id"];
                NSString *sessionId = [myAccountsArray[index] valueForKey:@"session_id"];
                NSString *localeId = [myAccountsArray[index] valueForKey:@"locale_id"];
                NSString *deviceID = [myAccountsArray[index] valueForKey:@"device_id"];
                NSString *clientUrl = [myAccountsArray[index] valueForKey:@"client_url"];
                NSString *cvsUrl = [myAccountsArray[index] valueForKey:@"cvs_url"];
                NSString *authIndFilePath = [NSString stringWithFormat:@"%@/%@/%@/%@/auth_indication.txt", directory, [self GetAppName], clientId, countryCode];
                if([fileManager fileExistsAtPath:authIndFilePath] == YES) {
                    NSData *fileData = [NSData dataWithContentsOfFile:authIndFilePath];
                    NSMutableDictionary *fileDict = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableContainers error:nil];
                    NSString *deviceStatus = fileDict[@"validDevice"];
                    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:authIndFilePath error:nil];
                    NSDateFormatter *dateFormatter = [self getCurrentDateTime];
                    [dateFormatter setDateFormat:@"yyyyMMdd"];
                    NSString *lastModified = [dateFormatter stringFromDate:[attributes fileModificationDate]];
                    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
                    int lastModifiedInt = [lastModified intValue];
                    int currentDateInt = [currentDate intValue];
                    if([deviceStatus isEqualToString:@"nostatus"] || lastModifiedInt != currentDateInt) {
                        [self triggerAuthenticationServices:clientId countryCode:countryCode userId:userId sessionId:sessionId localeId:localeId deviceID:deviceID clientUrl:clientUrl cvsUrl:cvsUrl authIndFilePath:authIndFilePath];
                    }
                } else {
                    [self triggerAuthenticationServices:clientId countryCode:countryCode userId:userId sessionId:sessionId localeId:localeId deviceID:deviceID clientUrl:clientUrl cvsUrl:cvsUrl authIndFilePath:authIndFilePath];
                }
            }
        }
    } @catch (NSException *exception) {
        NSLog(@"Exception : %@", exception.description);
    }
}

- (void)triggerAuthenticationServices:(NSString *)clientId  countryCode:(NSString *)countryCode  userId:(NSString *)userId  sessionId:(NSString *)sessionId  localeId:(NSString *)localeId  deviceID:(NSString *)deviceID  clientUrl:(NSString *)clientUrl  cvsUrl:(NSString *)cvsUrl authIndFilePath:(NSString *)authIndFilePath {
    @try {
        NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *jsonError;
        NSString *authAspx = [NSString stringWithFormat:@"%@/get_auth_indication.aspx", cvsUrl];
        NSString *deviceAspx = [NSString stringWithFormat:@"%@/security/validate_device.aspx", clientUrl];
        NSString *authContent = [NSString stringWithFormat:@"<inputparam><context><sessionId>%@</sessionId><userId>%@</userId><client_id>%@</client_id><locale_id>%@</locale_id><country_code>%@</country_code></context></inputparam>",sessionId, userId, clientId, localeId, countryCode];
        NSString *deviceContent = [NSString stringWithFormat:@"<document><context><sessionId>%@</sessionId><userId>%@</userId><client_id>%@</client_id><locale_id>%@</locale_id><country_code>%@</country_code><inputparam><p_device_id>%@</p_device_id><p_company_id>%@</p_company_id><p_country_code>%@</p_country_code></inputparam></context></document>",sessionId, userId, clientId, localeId, countryCode, deviceID, clientId, countryCode];
        NSMutableURLRequest *authRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:authAspx]];
        [authRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];
        [authRequest setHTTPMethod : @"POST"];
        [authRequest setHTTPBody : [authContent dataUsingEncoding:NSUTF8StringEncoding]];
        NSURLResponse *authResponse;
        NSData *authResponseData = [NSURLConnection sendSynchronousRequest:authRequest returningResponse:&authResponse error:&jsonError];
        NSString *responseString = [[NSString alloc] initWithData:authResponseData encoding:NSUTF8StringEncoding];
        NSMutableDictionary * mutableDict = [[NSMutableDictionary alloc] init];
        mutableDict = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
        //For device authentication
        @try {
            NSData *deviceData = [deviceContent dataUsingEncoding:NSUTF8StringEncoding];
            NSMutableURLRequest *deviceRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:deviceAspx]];
            [deviceRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];
            [deviceRequest setHTTPMethod : @"POST"];
            [deviceRequest setHTTPBody : deviceData];
            NSURLResponse *deviceResponse;
            NSData *deviceResponseData = [NSURLConnection sendSynchronousRequest:deviceRequest returningResponse:&deviceResponse error:nil];
            if (deviceResponseData != nil) {
                NSString *xmlFile = [NSString stringWithFormat:@"%@/%@/%@/%@/resp.xml", directory, [self GetAppName], clientId, countryCode];
                [deviceResponseData writeToFile:xmlFile atomically:true];
                [XMLConverter convertXMLFile:xmlFile completion:^(BOOL success, NSDictionary *dictionary, NSError *error)
                 {
                     if (success) {
                         NSDictionary *documentDict = [dictionary objectForKey:@"document"];
                         NSDictionary *context = [documentDict objectForKey:@"context"];
                         NSDictionary *outputparam = [context objectForKey:@"outputparam"];
                         NSString *p_valid_device_ind = [outputparam objectForKey:@"p_valid_device_ind"];
                         NSMutableDictionary * deviceDict = [[NSMutableDictionary alloc] init];
                         [deviceDict setValue:mutableDict[@"appVersion"] forKey:@"appVersion"];
                         [deviceDict setValue:mutableDict[@"cvsRefresh"] forKey:@"cvsRefresh"];
                         [deviceDict setValue:p_valid_device_ind forKey:@"validDevice"];
                         NSData *jsonData = [NSJSONSerialization dataWithJSONObject:deviceDict options:NSJSONWritingPrettyPrinted error:nil];
                         [jsonData writeToFile:authIndFilePath atomically:true];
                     }
                 }];
            } else {
                NSMutableDictionary * deviceDict = [[NSMutableDictionary alloc] init];
                [deviceDict setValue:mutableDict[@"appVersion"] forKey:@"appVersion"];
                [deviceDict setValue:mutableDict[@"cvsRefresh"] forKey:@"cvsRefresh"];
                [deviceDict setValue:@"nostatus" forKey:@"validDevice"];
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:deviceDict options:NSJSONWritingPrettyPrinted error:nil];
                [jsonData writeToFile:authIndFilePath atomically:true];
            }
        } @catch (NSException *exception) {
            NSMutableDictionary * deviceDict = [[NSMutableDictionary alloc] init];
            [deviceDict setValue:mutableDict[@"appVersion"] forKey:@"appVersion"];
            [deviceDict setValue:mutableDict[@"cvsRefresh"] forKey:@"cvsRefresh"];
            [deviceDict setValue:@"nostatus" forKey:@"validDevice"];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:deviceDict options:NSJSONWritingPrettyPrinted error:nil];
            [jsonData writeToFile:authIndFilePath atomically:true];
        }
    } @catch (NSException *exception) {
        NSLog(@"Exception : %@", exception.description);
    }
}

- (void)SendLocation {
    [self.commandDelegate runInBackground:^{
        @try {
            NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *locationFilePath = [NSString stringWithFormat:@"%@/%@/MyLocation.txt", directory, [self GetAppName]];
            NSString *lastKnownPath = [NSString stringWithFormat:@"%@/%@/LastKnownLocation.txt", directory, [self GetAppName]];
            NSData *fileContents = [[NSData alloc] init];
            NSFileManager *filemanager = [NSFileManager defaultManager];
            if([filemanager fileExistsAtPath:locationFilePath] != YES){
                [fileContents writeToFile:locationFilePath atomically:true];
            }
            double lat = self.locationManager.location.coordinate.latitude;
            double lngt = self.locationManager.location.coordinate.longitude;
            NSDateFormatter *dateFormatter = [self getCurrentDateTime];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *content = [NSString stringWithFormat:@"%f,%f,%@\n", lat, lngt, [dateFormatter stringFromDate:[NSDate date]]];
            //Appending Locations in MyLocation.txt file
            NSFileHandle *myLocationFileHandle = [NSFileHandle fileHandleForWritingAtPath:locationFilePath];
            [myLocationFileHandle seekToEndOfFile];
            [myLocationFileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
            [myLocationFileHandle closeFile];
            //Updating Locations in LastKnownLocation.txt file
            NSData *lastKnownLocationData = [content dataUsingEncoding:NSUTF8StringEncoding];
            [lastKnownLocationData writeToFile:lastKnownPath atomically:true];
            InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
            NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
            if(networkStatus == NotReachable){
            } else {
                NSError *error;
                NSArray *myAccountsArray = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]] encoding:NSUTF8StringEncoding error:&error] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error];
                for( int index = 0; index < [myAccountsArray count]; index++ ) {
                    NSString *clientId = [myAccountsArray[index] valueForKey:@"client_id"];
                    NSString *countryCode = [myAccountsArray[index] valueForKey:@"country_code"];
                    NSString *deviceID = [myAccountsArray[index] valueForKey:@"device_id"];
                    NSString *clientUrl = [myAccountsArray[index] valueForKey:@"client_url"];
                    NSString *locationData = [NSString stringWithContentsOfFile:locationFilePath encoding:NSUTF8StringEncoding error:&error];
                    NSString *baseURL = [NSString stringWithFormat:@"%@/common/components/GeoLocation/update_device_location_offline.aspx", clientUrl];
                    NSString *content = [NSString stringWithFormat:@"<location_xml><client_id>%@</client_id><country_code>%@</country_code><device_id>%@</device_id><location>%@</location></location_xml>", clientId, countryCode, deviceID, locationData];
                    NSData *inputData = [content dataUsingEncoding:NSUTF8StringEncoding];
                    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:baseURL]];
                    [request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];
                    [request setHTTPMethod : @"POST"];
                    [request setHTTPBody : inputData];
                    [NSURLConnection connectionWithRequest:request delegate:self];
                    // Emptying the text file
                    [[NSData data] writeToFile:locationFilePath atomically:true];
                }
            }
        } @catch (NSException *exception) {
            NSLog(@"SendLocation Exception is : %@", exception.description);
        }
    }];
}

- (void)GetLocation:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
        CDVPluginResult *result = nil;
        @try {
            NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString * filePath = [NSString stringWithFormat:@"%@/%@%@",directory,[self GetAppName],@"/LastKnownLocation.txt"];
            NSError * error;
            NSString * locationData = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
            NSArray * mySplit = [locationData componentsSeparatedByString:@","];
            NSString * locationString = [NSString stringWithFormat:@"{\"lat\":\"%@\",\"lon\":\"%@\"}", [mySplit objectAtIndex:0], [mySplit objectAtIndex:1]];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:locationString];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        } @catch (NSException * exception) {
            NSString * failReason = [NSString stringWithFormat:@"%@\n%@\n%@",exception.name, exception.reason, exception.description ];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:failReason];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        }
    }];
}

- (void)timeReader
{
    [self.commandDelegate runInBackground:^{
        @try {
            NSString *docdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *folderPath = [NSString stringWithFormat:@"%@/%@/time_profile.txt", docdir, [self GetAppName]];
            NSData *data = [NSData dataWithContentsOfFile:folderPath];
            NSError *jsonError = nil;
            NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
            NSString *serverDate = dict[@"serverDate"];
            NSDateFormatter * dateFormatter = [self getCurrentDateTime];
            [dateFormatter setDateFormat:@"yyyy,MM,dd,HH,mm,ss"];
            NSDate *date = [dateFormatter dateFromString:serverDate];
            NSDate *addedDate = [date dateByAddingTimeInterval:(1*60)];
            NSString *dateString = [dateFormatter stringFromDate:addedDate];
            dict[@"serverDate"] = dateString;
            NSLog(@"Time from timeReader : %@", dict[@"serverDate"]);
            NSData *fileContents = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            [fileContents writeToFile:folderPath atomically:true];
        } @catch (NSException *exception) {
            NSLog(@"timeReader Exception is : %@", exception.description);
        }
    }];
}

- (void)CheckSumIndicatorResult {
    [self.commandDelegate runInBackground:^{
        @try
        {
            InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
            NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
            if(networkStatus != NotReachable){
                NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *rootFolderPath = [NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]];
                NSError *error = nil;
                NSString *myAccountsContents = [NSString stringWithContentsOfFile:rootFolderPath encoding:NSUTF8StringEncoding error:&error];
                NSData *myAccountsData = [myAccountsContents dataUsingEncoding:NSUTF8StringEncoding];
                NSArray *myAccountsArray = [NSJSONSerialization JSONObjectWithData:myAccountsData options: NSJSONReadingMutableContainers error: &error];
                for(int index = 0; index < [myAccountsArray count]; index++) {
                    NSString *clientId = [myAccountsArray[index] valueForKey:@"client_id"];
                    NSString *countryCode = [myAccountsArray[index] valueForKey:@"country_code"];
                    NSString *userId = [myAccountsArray[index] valueForKey:@"user_id"];
                    NSString *empId = [myAccountsArray[index] valueForKey:@"emp_id"];
                    NSString *sessionId = [myAccountsArray[index] valueForKey:@"session_id"];
                    NSString *localeId = [myAccountsArray[index] valueForKey:@"locale_id"];
                    NSString *clientUrl = [myAccountsArray[index] valueForKey:@"client_url"];
                    NSString *request_path = [NSString stringWithFormat:@"%@/JSONServiceEndpoint.aspx?appName=common_modules&serviceName=retrieve_listof_values_for_searchcondition&path=context/outputparam", clientUrl];
                    NSString *checkSumPath = [NSString stringWithFormat:@"%@/%@/%@/database/checksum_value.txt", directory, clientId, countryCode];
                    NSLog(@"checkSum Path %@", checkSumPath);
                    NSData *data = [NSData dataWithContentsOfFile:checkSumPath];
                    NSString *checksum_value, *refresh_ind;
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    if([fileManager fileExistsAtPath:checkSumPath] == YES){
                        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        checksum_value = dict[@"checksum_value"];
                        refresh_ind = dict[@"refresh_ind"];
                    } else {
                        checksum_value = @"";
                        refresh_ind = @"";
                    }
                    if([refresh_ind isEqual: @""] || [refresh_ind isEqual:@"false"]){
                        NSString *content = [NSString stringWithFormat:@"{\"context\":{\"sessionId\":\"%@\",\"userId\":\"%@\",\"client_id\":\"%@\",\"locale_id\":\"%@\",\"country_code\":\"%@\",\"inputparam\":{\"p_inputparam_xml\":\"<inputparam><lov_code_type>VALIDATE_CHECKSUM</lov_code_type><search_field_1>%@</search_field_1><search_field_2>%@</search_field_2><search_field_3>MOBILE</search_field_3></inputparam>\"}}}",sessionId, userId, clientId, localeId, countryCode, checksum_value, empId];
                        NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
                        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:request_path]];
                        [request setValue:@"text/json" forHTTPHeaderField:@"Content-type"];
                        [request setHTTPMethod : @"POST"];
                        [request setHTTPBody : data];
                        NSURLResponse *response;
                        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
                        NSString *replacedString = responseString;
                        replacedString = [replacedString stringByReplacingOccurrencesOfString:@"[" withString:@""];
                        replacedString = [replacedString stringByReplacingOccurrencesOfString:@"]" withString:@""];
                        NSData *finalCheckSumData = [replacedString dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *json = [[NSDictionary alloc] init];
                        json = [NSJSONSerialization JSONObjectWithData:finalCheckSumData options:kNilOptions error:&error];
                        //Check if it is valid JSON or not
                        if ([NSJSONSerialization JSONObjectWithData:finalCheckSumData
                                                            options:kNilOptions
                                                              error:&error] == nil) {
                        } else {
                            //Check given response is valid Checksum data or Exception..
                            if([json objectForKey:@"refresh_ind"]){
                                [finalCheckSumData writeToFile:checkSumPath atomically:true];
                                NSString *date, *hour, *minute;
                                NSData *responseJson = [replacedString dataUsingEncoding:NSUTF8StringEncoding];
                                NSMutableDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:responseJson options:NSJSONReadingMutableContainers error:&error];
                                date = [NSString stringWithFormat:@"%@", dictionary[@"serverDate"]];
                                hour = [NSString stringWithFormat:@"%@", dictionary[@"serverHour"]];
                                minute = [NSString stringWithFormat:@"%@", dictionary[@"serverMinute"]];
                                [self timeValues:date hour:hour minute:minute];
                            }
                        }
                    }
                }
            }
        } @catch (NSException *exception) {
            NSLog(@"CheckSumIndicatorResult Exception is : %@", exception.description);
        }
    }];
}

- (void)RefreshTimeProfile:(CDVInvokedUrlCommand*)command
{
    @try {
        [self.commandDelegate runInBackground:^{
            NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
            NSString *date = dict[@"serverDate"];
            NSString *hour = dict[@"serverHour"];
            NSString *minute = dict[@"serverMinute"];
            [self timeValues:date hour:hour minute:minute];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        }];
    } @catch (NSException *exception) {
        NSLog(@"RefreshTimeProfile Exception is : %@", exception.description);
    }
}

-(void)timeValues:(NSString *)date hour:(NSString *)hour minute:(NSString *)minute
{
    @try {
        NSString *serverDate = [NSString stringWithFormat:@"%@,%@,%@,00", date, hour, minute];
        NSDateFormatter * dateFormatter = [self getCurrentDateTime];
        [dateFormatter setDateFormat:@"yyyy,MM,dd,HH,mm,ss"];
        NSDate *getDate = [dateFormatter dateFromString:serverDate];
        NSString *deviceDate = [dateFormatter stringFromDate:[NSDate date]];
        NSString *finalServerDate = [dateFormatter stringFromDate:getDate];
        NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];
        [dictionary setValue:finalServerDate forKey:@"serverDate"];
        [dictionary setValue:finalServerDate forKey:@"initServerDate"];
        [dictionary setValue:deviceDate forKey:@"initDeviceDate"];
        NSString *docdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *time_profile = [NSString stringWithFormat:@"%@/%@/time_profile.txt", docdir, [self GetAppName]];
        NSLog(@"time profile path : %@", time_profile);
        NSData *fileContents = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
        [fileContents writeToFile:time_profile atomically:true];
    } @catch (NSException *exception) {
        NSLog(@"timeValues Exception is : %@", exception.description);
    }
}

- (id)getCurrentDateTime {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[NSLocale alloc]
                        initWithLocaleIdentifier:@"US"];
    [dateFormatter setLocale:locale];
    return dateFormatter;
}

- (void)GetNewDate:(CDVInvokedUrlCommand*)command
{
    @try {
        [self.commandDelegate runInBackground:^{
            NSString *docdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *time_profile = [NSString stringWithFormat:@"%@/%@/time_profile.txt", docdir,[self GetAppName]];
            NSData *user_data = [NSData dataWithContentsOfFile:time_profile];
            NSError *jsonError = nil;
            NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:user_data options:NSJSONReadingMutableContainers error:&jsonError];
            NSString *serverDateString = dict[@"serverDate"];
            NSDateFormatter * dateFormatter = [self getCurrentDateTime];
            [dateFormatter setDateFormat:@"yyyy,MM,dd,HH,mm,ss"];
            NSDate *deviceDate = [NSDate date];
            NSDate *serverDate = [dateFormatter dateFromString:serverDateString];
            NSTimeInterval timeDifference = [deviceDate timeIntervalSinceDate:serverDate];
            NSLog(@"%f", timeDifference);
            //NSTimeInterval timeDiff = [deviceDate timeIntervalSinceReferenceDate] - [getDate timeIntervalSinceReferenceDate];
            if(timeDifference > 0){
                serverDate = [serverDate dateByAddingTimeInterval:timeDifference];
            }
            NSString *finalServerDate = [dateFormatter stringFromDate:serverDate];
            NSLog(@"finalServerDate : %@", finalServerDate);
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:finalServerDate];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        }];
    } @catch (NSException *exception) {
        NSLog(@"GetNewDate Exception is : %@", exception.description);
    }
}

- (void)CheckLocation:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
        CDVPluginResult *result = nil;
        @try {
            BOOL isEnabled = false;
            if([CLLocationManager locationServicesEnabled] &&
               [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied)
            {
                isEnabled = true;
            } else {
                isEnabled = false;
            }
            NSString *serviceResult = [NSString stringWithFormat:@"%s", isEnabled ? "true" : "false"];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:serviceResult];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        } @catch (NSException *exception) {
            NSString *fail_reason = [NSString stringWithFormat:@"%@\n%@\n%@",exception.name, exception.reason, exception.description ];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fail_reason];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
            NSLog(@"CheckLocation Exception is : %@", exception.description);
        }
    }];
}

- (void)CopyFile:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        @try {
            for(int index = 0; index < [[command arguments] count]; index++) {
                NSMutableDictionary * dict = [[command arguments] objectAtIndex:index];
                NSString *directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
                NSString *srcPath = dict[@"srcPath"];
                NSString *toPath = [NSString stringWithFormat:@"%@/%@", directory, dict[@"desPath"]];
                NSString *queueAttachPath = [NSString stringWithFormat:@"%@/%@", directory, dict[@"queueAttachPath"]];
                NSError *error;
                if (![[NSFileManager defaultManager] fileExistsAtPath:toPath]) {
                    [[NSFileManager defaultManager] createDirectoryAtPath:toPath withIntermediateDirectories:YES attributes:nil error:nil];
                }
                if (![[NSFileManager defaultManager] fileExistsAtPath:queueAttachPath]){
                    [[NSFileManager defaultManager] createDirectoryAtPath:queueAttachPath withIntermediateDirectories:YES attributes:nil error:nil];
                }
                NSString *srcFilePath = [NSString stringWithFormat:@"%@/%@", srcPath, dict[@"srcFile"]];
                NSString *destFilePath = [NSString stringWithFormat:@"%@/%@", toPath, dict[@"desFile"]];
                NSString *queueAttachCopyPath = [NSString stringWithFormat:@"%@/%@", queueAttachPath, dict[@"desFile"]];
                if([[NSFileManager defaultManager] fileExistsAtPath:srcFilePath]) {
                    if([[NSFileManager defaultManager] copyItemAtPath:srcFilePath toPath:destFilePath error:&error]==YES)
                    {
                        NSLog(@"File copied..");
                    }
                    if([[NSFileManager defaultManager] copyItemAtPath:srcFilePath toPath:queueAttachCopyPath error:&error]==YES)
                    {
                        NSLog(@"File copied..");
                    }
                } else {
                    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
                }
            }
            [self RemoveFilesFromDirectory];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        } @catch (NSException *exception) {
            NSLog(@"CopyFile Exception is : %@", exception.description);
        }
    }];
}

- (void)DespatchQueueNew {
    [self.commandDelegate runInBackground:^{
        @try {
            NSString* directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            NSError *jsonError = nil;
            NSString *queuePath = [NSString stringWithFormat:@"%@/%@/database/queue", directory,[self GetAppName]];
            NSLog(@"Queue Path : %@", queuePath);
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:queuePath]) {
                NSArray *holeFileList = [fileManager contentsOfDirectoryAtPath:queuePath error:&jsonError];
                NSMutableArray *queueFileList = [holeFileList mutableCopy];
                if ([queueFileList containsObject:@".DS_Store"]) {
                    [queueFileList removeObject:@".DS_Store"];
                }
                //To check internet is available or not
                InternetConnection *networkReachability = [InternetConnection reachabilityForInternetConnection];
                NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
                if(networkStatus != NotReachable) {
                    //NSInteger indexValue = [fileList indexOfObject:@".DS_Store"];
                    for( int index = 0; index < [queueFileList count]; index++ ) {
                        NSMutableDictionary *bckpDataFullContent;
                        NSString *currentFile = [NSString stringWithFormat:@"%@/%@", queuePath, queueFileList[index]];
                        NSString *contents =[NSString stringWithContentsOfFile:currentFile encoding:NSUTF8StringEncoding error:nil];
                        NSData *data = [contents dataUsingEncoding:NSUTF8StringEncoding];
                        NSError *jsonError = nil;
                        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
                        NSString *requestUrl = dict[@"url"];
                        NSString *sendData = dict[@"input"];
                        NSString *fileType = dict[@"type"];
                        NSString *sendFileBasePath = dict[@"filepath"];
                        NSString *sendFileName = dict[@"filename"];
                        NSString *method = dict[@"method"];
                        NSString *keyValue = dict[@"key"];
                       // NSString *subKeyValue = contextString[@"subkey"];
                        if([method isEqualToString:@"read"]){
                            NSString *inputString = [dict objectForKey:@"input"];
                            NSData *inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
                            NSMutableDictionary * inputDict = [NSJSONSerialization JSONObjectWithData:inputData options:NSJSONReadingMutableContainers error:&jsonError];
                            NSMutableDictionary *contextString = [inputDict objectForKey:@"context"];
                            NSString *clientID = contextString[@"client_id"];
                            NSString *countryCode = contextString[@"country_code"];
                            NSString *backupFilePath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/bckp_%@.txt",directory, [self GetAppName],clientID, countryCode, keyValue];
                            //send data to server
                            NSData *dataToServer = [sendData dataUsingEncoding:NSUTF8StringEncoding];
                            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];
                            [request setValue:@"text/json" forHTTPHeaderField:@"Content-type"];
                            [request setHTTPMethod : @"POST"];
                            [request setHTTPBody : dataToServer];
                            //Get Response from url
                            NSURLResponse *response;
                            NSError *responseError;
                            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
                            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
                            NSFileManager *filemanager = [NSFileManager defaultManager];
                            //check if file is not exists
                            if([filemanager fileExistsAtPath:backupFilePath] == YES){
                                //Read backp + keyValue file and convert it to a JSON object
                                NSData *data = [NSData dataWithContentsOfFile:backupFilePath];
                                bckpDataFullContent = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
                            } else {
                                //make empty JSON
                                bckpDataFullContent = [[NSMutableDictionary alloc] init];
                            }
                            //write response to backup file where subkey matches in queue mngr file.
                            NSData *dddddd = [responseString dataUsingEncoding:NSUTF8StringEncoding];
                            id json = [NSJSONSerialization JSONObjectWithData:dddddd options:0 error:nil];
                            [bckpDataFullContent setValue:json forKey:dict[@"subkey"]];
                            NSData *bbbbb = [NSJSONSerialization dataWithJSONObject:bckpDataFullContent options:0 error:nil];
                            [bbbbb writeToFile:backupFilePath atomically:true];
                        } else {
                            if([fileType isEqualToString:@"file"]){
                                @try {
                                    NSString *requestFilePath = [NSString stringWithFormat:@"%@/%@/", directory, sendFileBasePath];
                                    NSString *filePathofImage = [requestFilePath stringByAppendingPathComponent:sendFileName];
                                    if ([[NSFileManager defaultManager] fileExistsAtPath:filePathofImage]){
                                        NSString *urlString =[NSString stringWithFormat:@"%@&filename=%@",requestUrl, sendFileName];
                                        NSURL *url=[NSURL URLWithString:[[NSString stringWithFormat:@"%@", urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                                        NSMutableURLRequest *fileRequest = [[NSMutableURLRequest alloc] init];
                                        [fileRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
                                        [fileRequest setHTTPShouldHandleCookies:NO];
                                        [fileRequest setTimeoutInterval:240];
                                        [fileRequest setHTTPMethod:@"POST"];
                                        NSString *boundary = @"---------------------------14737809831466499882746641449";
                                        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
                                        [fileRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
                                        NSString *fileExtension = [[filePathofImage pathExtension] lowercaseString];
                                        UIImage *yourImage= [UIImage imageNamed:filePathofImage];
                                        NSData *imageData = UIImageJPEGRepresentation(yourImage, 1.0);
                                        NSMutableData *body = [NSMutableData data];
                                        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                                        if (imageData)
                                        [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"",sendFileName,@"\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
                                        NSString *imgMimeType = [NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self contentTypeForImageData:fileExtension]];
                                        [body appendData:[imgMimeType dataUsingEncoding:NSUTF8StringEncoding]];
                                        if (imageData)
                                        [body appendData:[NSData dataWithData:imageData]];
                                        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                                        [fileRequest setHTTPBody:body];
                                        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
                                        [fileRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
                                        [fileRequest setURL:url];
                                        [NSURLConnection connectionWithRequest:fileRequest delegate:self];
                                    }
                                } @catch (NSException *exception) {
                                    NSLog(@"File Sending Exception : %@", exception.description);
                                }
                            } else {
                                NSData *dataToServer = [sendData dataUsingEncoding:NSUTF8StringEncoding];
                                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];
                                [request setHTTPMethod : @"POST"];
                                [request setValue:@"text/json" forHTTPHeaderField:@"Content-type"];
                                [request setHTTPBody : dataToServer];
                                [NSURLConnection connectionWithRequest:request delegate:self];
                            }
                        }
                        [fileManager removeItemAtPath:currentFile error:&jsonError];
                    }
                }
            }
        } @catch (NSException *exception) {
            NSLog(@"DespatchQueueNew Exception is : %@", exception.description);
        }
    }];
}

- (void)GetSyncIndicator:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult *result = nil;
    @try {
        NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
        NSString *client_id = dict[@"client_id"];
        NSString *country_code = dict[@"country_code"];
        NSString *user_id = dict[@"user_id"];
        NSString *client_url = dict[@"client_url"];
        BOOL isEnabled = false;
        NSString *requestUrl = [NSString stringWithFormat:@"%@/common/components/QueueManager/GetSyncInd.aspx?client_id=%@&country_code=%@&user_id=%@", client_url, client_id, country_code, user_id];
        NSString *returnedIndication = @"";
        NSString *directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *oldQueuePath = [NSString stringWithFormat:@"%@/%@/database/queue", directory,[self GetAppName]];
        NSString *newQueuePath = [NSString stringWithFormat:@"%@/%@/%@/%@/database/queue", directory,[self GetAppName], client_id, country_code];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:oldQueuePath]) {
            NSArray *oldQueueFiles = [fileManager contentsOfDirectoryAtPath:oldQueuePath error:nil];
            NSMutableArray *oldQueueFilesMut = [oldQueueFiles mutableCopy];
            if ([oldQueueFilesMut containsObject:@".DS_Store"]) {
                [oldQueueFilesMut removeObject:@".DS_Store"];
            }
            if (oldQueueFilesMut == nil || [oldQueueFilesMut count] == 0) {
                isEnabled = true;
            }
        } else {
            isEnabled = true;
        }
        if (isEnabled) {
            if ([fileManager fileExistsAtPath:newQueuePath]) {
                NSArray *newQueueFiles = [fileManager contentsOfDirectoryAtPath:newQueuePath error:nil];
                NSMutableArray *newQueueFilesMut = [newQueueFiles mutableCopy];
                if ([newQueueFilesMut containsObject:@".DS_Store"]) {
                    [newQueueFilesMut removeObject:@".DS_Store"];
                }
                if (newQueueFilesMut == nil || [newQueueFilesMut count] != 0) {
                    isEnabled = false;
                }
            }
        }
        if (isEnabled) {
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];
            [request setValue:@"application/text" forHTTPHeaderField:@"Content-type"];
            [request setHTTPMethod : @"POST"];
            //Get Response from url
            NSURLResponse *response;
            NSError *responseError;
            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            returnedIndication = responseString;
            if([returnedIndication isEqualToString:@"true"]) {
                isEnabled = true;
            } else {
                isEnabled = false;
            }
        }
        NSString *serviceResult = [NSString stringWithFormat:@"%s", isEnabled ? "true" : "false"];
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:serviceResult];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } @catch (NSException *exception) {
        NSString *fail_reason = [NSString stringWithFormat:@"%@\n%@\n%@",exception.name, exception.reason, exception.description ];
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fail_reason];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
        NSLog(@"CheckLocation Exception is : %@", exception.description);
    }
}

- (void)FileChooser:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
        ipc= [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
        if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone){
            [top presentViewController:ipc animated:YES completion: nil];
            self.callbackIdForImagePicker = command.callbackId;
        }
        else
        {
            popover=[[UIPopoverController alloc]initWithContentViewController:ipc];
            CGRect myFrame = [top.view frame];
            [popover presentPopoverFromRect:myFrame inView:top.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }];
}

- (NSString *)contentTypeForImageData:(NSString *)string
{
    NSString *c;
    if ([string isEqualToString:@"jpg"]){
        c = @"image/jpeg";
    } else if ([string isEqualToString:@"png"]) {
        c = @"image/png";
    } else if ([string isEqualToString:@"gif"]){
        c = @"image/gif";
    } else if ([string isEqualToString:@"pdf"]){
        c = @"application/pdf";
    } else if ([string isEqualToString:@"txt"]){
        c = @"application/txt";
    }
    return c;
}

#pragma mark - ImagePickerController Delegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if ([picker isEqual:ipc]) {
        if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
            [picker dismissViewControllerAnimated:YES completion:nil];
        } else {
            [popover dismissPopoverAnimated:YES];
        }
        UIImageView *ivPickedImage = [[UIImageView alloc] init];
        ivPickedImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSURL *refURL = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
        // define the block to call when we get the asset based on the url (below)
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
        {
            ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
            NSString* directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            NSString *dest = [NSString stringWithFormat:@"%@/%@/%@",directory,[self GetAppName],@"/dest"];
            if (![[NSFileManager defaultManager] fileExistsAtPath:dest]){
                [[NSFileManager defaultManager] createDirectoryAtPath:dest withIntermediateDirectories:YES attributes:nil error:nil];
            }
            NSString *destination = [NSString stringWithFormat:@"%@/%@", dest, [imageRep filename]];
            UIImage *img = ivPickedImage.image;
            NSData * data = UIImageJPEGRepresentation(img, 0.3);
            long imgSize = data.length;
            NSString *strImageSize = [NSString stringWithFormat:@"%ld", imgSize];
            NSString *extension = [[NSString stringWithFormat:@".%@",[destination pathExtension]] lowercaseString];
            [data writeToFile:destination atomically:YES];
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
            [dict setValue:[destination stringByDeletingLastPathComponent] forKey:@"filePath"];
            [dict setValue:[destination lastPathComponent] forKey:@"fileName"];
            [dict setValue:strImageSize forKey:@"fileSize"];
            [dict setValue:extension forKey:@"fileExtension"];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dict];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
        };
        // get the asset library and fetch the asset based on the ref url (pass in block above)
        NSLog(@"refURL : %@", refURL);
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    } else if ([picker isEqual: cameraOpen] || [picker isEqual:imagePicker]) {
        if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
            [picker dismissViewControllerAnimated:YES completion:nil];
        } else {
            [popover dismissPopoverAnimated:YES];
        }
        UIImageView *ivPickedImage = [[UIImageView alloc] init];
        ivPickedImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSURL *refURL = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
        // define the block to call when we get the asset based on the url (below)
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
        {
            NSData *imageData = UIImageJPEGRepresentation(ivPickedImage.image, 0.3);
            NSString * base64String = [imageData base64EncodedStringWithOptions:0];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:base64String];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
        };
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    } else if ([picker isEqual:liveCamera]) {
        if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) {
            [picker dismissViewControllerAnimated:YES completion:nil];
        } else {
            [popover dismissPopoverAnimated:YES];
        }
        UIImageView *ivPickedImage = [[UIImageView alloc] init];
        ivPickedImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSURL *refURL = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
        // define the block to call when we get the asset based on the url (below)
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) {
            UIImage *image = ivPickedImage.image;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *directory = [paths objectAtIndex:0];
            NSString* appRootPath = [directory stringByAppendingPathComponent:[self GetAppName]];
            NSString *imagesFolderPath = [appRootPath stringByAppendingPathComponent:@"images"];
            if (![[NSFileManager defaultManager] fileExistsAtPath:imagesFolderPath]){
                [[NSFileManager defaultManager] createDirectoryAtPath:imagesFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            NSDateFormatter *dateFormatter = [self getCurrentDateTime];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *fileName = [NSString stringWithFormat:@"%@.png", [dateFormatter stringFromDate:[NSDate date]]];
            NSString* imageSavedPath = [imagesFolderPath stringByAppendingPathComponent:fileName];
            NSData* imageData = UIImageJPEGRepresentation(image, 0.3);
            [imageData writeToFile:imageSavedPath atomically:YES];
            long imgSize = imageData.length;
            NSString *strImageSize = [NSString stringWithFormat:@"%ld", imgSize];
            NSString *extension = [[NSString stringWithFormat:@".%@",[imageSavedPath pathExtension]] lowercaseString];
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
            [dict setValue:[imageSavedPath stringByDeletingLastPathComponent] forKey:@"filePath"];
            [dict setValue:[imageSavedPath lastPathComponent] forKey:@"fileName"];
            [dict setValue:strImageSize forKey:@"fileSize"];
            [dict setValue:extension forKey:@"fileExtension"];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dict];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
        };
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
}

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

- (void)UpdateNew:(CDVInvokedUrlCommand*)command {
    NSString *iTunesLink = @"https://itunes.apple.com/us/app/mservice/id945991789?mt=8";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
}

//For App update version
- (void)UpdateChoice:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        @try {
            self.callbackIdForAppUpdate = command.callbackId;
            NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
            NSString *message = [NSString stringWithFormat:@"Your mservice version is %@. There is an updated version  %@.%@ available. Please update.", dict[@"appVersion"], dict[@"softwareProductVersion"], dict[@"softwareProductSubVersion"]];
            UIViewController *viewControllerChoice = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
            alertChoice = [[UIAlertController alloc] init];
            alertChoice = [UIAlertController
                           alertControllerWithTitle:@"Logout"
                           message:message
                           preferredStyle:UIAlertControllerStyleAlert];
            //Add Buttons
            UIAlertAction* yesButton = [UIAlertAction
                                        actionWithTitle:@"Not Now"
                                        style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction * action) {
                                            //Handle your yes please button action here
                                            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                                            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
                                        }];
            UIAlertAction* noButton = [UIAlertAction
                                       actionWithTitle:@"Update"
                                       style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction * action) {
                                           //Handle no, thanks button
                                           NSString *iTunesLink = @"https://itunes.apple.com/us/app/mservice/id945991789?mt=8";
                                           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
                                           CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                                           [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
                                       }];
            //Add your buttons to alert controller
            [alertChoice addAction:yesButton];
            [alertChoice addAction:noButton];
            [viewControllerChoice presentViewController:alertChoice animated:YES completion:nil];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
        } @catch (NSException *exception) {
            NSLog(@"Exception : %@", exception.description);
        }
    }];
}

- (void)UpdateConfirm:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        @try {
            self.callbackIdForAppUpdate = command.callbackId;
            NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
            NSString *message = [NSString stringWithFormat:@"Your mservice version is %@. There is an updated version  %@.%@ available. Please update.", dict[@"appVersion"], dict[@"softwareProductVersion"], dict[@"softwareProductSubVersion"]];
            UIViewController *viewControllerConfirm = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
            alertConfirm = [[UIAlertController alloc] init];
            alertConfirm = [UIAlertController
                                 alertControllerWithTitle:@"Update Confirm"
                                 message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* noButton = [UIAlertAction
                                       actionWithTitle:@"Update"
                                       style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction * action) {
                                           //Handle no, thanks button
                                           NSString *iTunesLink = @"https://itunes.apple.com/us/app/mservice/id945991789?mt=8";
                                           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
                                           CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                                           [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
                                       }];
            //Add your buttons to alert controller
            [alertConfirm addAction:noButton];
            [viewControllerConfirm presentViewController:alertConfirm animated:YES completion:nil];
        } @catch (NSException *exception) {
            NSLog(@"Exception : %@", exception.description);
        }
    }];
}

#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == [alertView cancelButtonIndex]){
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
        NSLog(@"Cancel button clicked.");
    } else {
        NSString *iTunesLink = @"https://itunes.apple.com/us/app/mservice/id945991789?mt=8";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
        [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForAppUpdate];
    }
}

-(CGRect)rectForView {
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    BOOL landscape = (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight);
    if(landscape){
        return CGRectMake( 0.0f, 0.0f, [UIScreen mainScreen].bounds.size.height, [[UIScreen mainScreen]bounds].size.width);
    }
    return CGRectMake( 0.0f, 0.0f, [[UIScreen mainScreen]bounds].size.width, [UIScreen mainScreen].bounds.size.height);
}

- (void)handleTapGesture:(UITapGestureRecognizer *)gesture
{
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [result setKeepCallbackAsBool:true];
    if (!spinnerIsFixed.boolValue) {
        [result setKeepCallbackAsBool:false];
        [self hide];
    }
    [self.commandDelegate sendPluginResult:result callbackId:spinnerCallbackId];
}

- (UIView *)overlay {
    if (!_overlay) {
        _overlay = [[UIView alloc] initWithFrame:self.rectForView];
        _overlay.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.60];
        _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        _indicator.center = _overlay.center;
        [_indicator startAnimating];
        [_overlay addSubview:_indicator];
        
        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
        [_overlay addGestureRecognizer: tapRecognizer];
    }
    return _overlay;
}

- (void)Spinner:(CDVInvokedUrlCommand *)command {
    NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
    NSNumber *spinnerInd = dict[@"show"];
    NSString *comapareString = dict[@"show"];
    if([comapareString isEqualToString:@"true"]) {
        spinnerCallbackId = command.callbackId;
        //If there is a loading mask yet we hide it
        [self hide];
        spinnerIsFixed = spinnerInd;
        UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        [rootViewController.view addSubview:self.overlay];
        //[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    } else {
        [self hide];
    }
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:result callbackId:self.successCallBackForSpinner];
}

- (void) hide {
    if (_overlay) {
        [self.indicator stopAnimating];
        [self.indicator removeFromSuperview];
        [self.overlay removeFromSuperview];
        _indicator = nil;
        _overlay = nil;
    }
}

#pragma mark - PRIVATE METHODS

- (NSString *)GetAppName {
    NSString *packageName = [[NSBundle mainBundle] bundleIdentifier];
    NSArray *splitedArray = [packageName componentsSeparatedByString:@"."];
    return splitedArray[2];
}

- (void)GetPackageName:(CDVInvokedUrlCommand*)command {
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:bundleIdentifier];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

-(NSString *)getAppRootFolderPathCopy {
    NSString * directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * rootFolderPath = [NSString stringWithFormat:@"%@/%@/my_accounts.txt", directory, [self GetAppName]];
    NSError * error;
    NSString * myAccountsContents = [NSString stringWithContentsOfFile:rootFolderPath encoding:NSUTF8StringEncoding error:&error];
    NSData * myAccountsData = [myAccountsContents dataUsingEncoding:NSUTF8StringEncoding];
    NSArray * myAccountsArray = [NSJSONSerialization JSONObjectWithData:myAccountsData options: NSJSONReadingMutableContainers error: &error];
    NSArray * filtered = [myAccountsArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"client_id LIKE[cd] %@", @"cjakson"]];
    NSString * client_id = [filtered[0] valueForKey:@"client_id"];
    NSString * country_code = [filtered[0] valueForKey:@"country_code"];
    NSString * finalRootPath = [NSString stringWithFormat:@"%@/%@/%@/%@", directory, [self GetAppName], client_id, country_code];
    return finalRootPath;
}
@end
