#import "mInterface.h"
#import "XMLConverter.h"
#import "InternetConnection.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Cordova/CDVViewController.h>
#import <objc/message.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include "TargetConditionals.h"

@implementation mInterface
@synthesize btnGallery;
@synthesize indicator = _indicator;
@synthesize overlay = _overlay;

-(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.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.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)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];
}

-(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];
}

//----------- APPVERSION PLUGIN -----------//
- (void)AppVersion:(CDVInvokedUrlCommand*)command {
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
    NSNumber *buildNumber = [infoDict objectForKey:@"CFBundleVersion"];
    NSDictionary *dict = @{@"version":appVersion,@"build":buildNumber};
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dict];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

//----------- TO GET DEVICE INFORMATIONS -----------//
- (NSString*)modelVersion
{
#if TARGET_IPHONE_SIMULATOR
    NSString* platform = NSProcessInfo.processInfo.environment[@"SIMULATOR_MODEL_IDENTIFIER"];
#else
    size_t size;
    
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char* machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString* platform = [NSString stringWithUTF8String:machine];
    free(machine);
#endif
    return platform;
}

- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device {
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    static NSString* UUID_KEY = @"CDVUUID";
    
    // Check user defaults first to maintain backwards compaitibility with previous versions
    // which didn't user identifierForVendor
    NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];
    if (app_uuid == nil) {
        if ([device respondsToSelector:@selector(identifierForVendor)]) {
            app_uuid = [[device identifierForVendor] UUIDString];
        } else {
            CFUUIDRef uuid = CFUUIDCreate(NULL);
            app_uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
            CFRelease(uuid);
        }
        
        [userDefaults setObject:app_uuid forKey:UUID_KEY];
        [userDefaults synchronize];
    }
    return app_uuid;
}

- (void)DeviceInfo:(CDVInvokedUrlCommand*)command {
    NSDictionary* deviceProperties = [self deviceProperties];
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (NSDictionary*)deviceProperties {
    UIDevice* device = [UIDevice currentDevice];
    return @{
             @"manufacturer": @"Apple",
             @"model": [device model],
             @"platform": @"iOS",
             @"version": [device systemVersion],
             @"uuid": [self uniqueAppInstanceIdentifier:device],
             @"cordova": [[self class] cordovaVersion],
             @"isVirtual": @([self isVirtual])
             };
}

+ (NSString*)cordovaVersion {
    return CDV_VERSION;
}

- (BOOL)isVirtual {
#if TARGET_OS_SIMULATOR
    return true;
#elif TARGET_IPHONE_SIMULATOR
    return true;
#else
    return false;
#endif
}
-(void)CreateDirectory:(CDVInvokedUrlCommand*)command {
    @try {
        NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
        NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error;
        NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:fullFilePath]) {
            [fileManager createDirectoryAtPath:fullFilePath withIntermediateDirectories:YES attributes:nil error:&error];
        }
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } @catch (NSException *exception) {
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to write file.."];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}

-(void)DeleteDirectory:(CDVInvokedUrlCommand*)command {
    @try {
        NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
        NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error;
        NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:fullFilePath]) {
            [fileManager removeItemAtPath:fullFilePath error:&error];
        }
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } @catch (NSException *exception) {
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to write file.."];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}
-(void)CreateFile:(CDVInvokedUrlCommand*)command {
    @try {
        NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
        NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSError *error;
        NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *theFileName = [fullFilePath lastPathComponent];
        NSArray *onlyPath = [fullFilePath componentsSeparatedByString:theFileName];
        if(![fileManager fileExistsAtPath:[onlyPath objectAtIndex:0]]) {
            [fileManager createDirectoryAtPath:[onlyPath objectAtIndex:0] withIntermediateDirectories:YES attributes:nil error:&error];
        }
        NSData *data = [dict[@"data"] dataUsingEncoding:NSUTF8StringEncoding];
        [data writeToFile:fullFilePath atomically:true];
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } @catch (NSException *exception) {
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to write file.."];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}

-(void)ReadFile:(CDVInvokedUrlCommand*)command {
    CDVPluginResult *result = nil;
    NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error;
    NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:fullFilePath]) {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No file found at the path to read.."];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } else {
        NSString *readData = [NSString stringWithContentsOfFile:fullFilePath encoding:NSUTF8StringEncoding error:&error];
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:readData];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}
-(void)DeleteFile:(CDVInvokedUrlCommand*)command {
    CDVPluginResult *result = nil;
    NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error;
    NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:fullFilePath]) {
        [fileManager removeItemAtPath:fullFilePath error:nil];
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } else {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No file found at the path to delete.."];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}

-(void)validateFile:(CDVInvokedUrlCommand*)command {
    CDVPluginResult *result = nil;
    NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error;
    NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", dir, dict[@"filePath"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:fullFilePath]) {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"true"];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    } else {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"false"];
        [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
    }
}

-(void)GetStorageRoot:(CDVInvokedUrlCommand*)command {
    NSURL *dirURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                           inDomain:NSUserDomainMask
                                                  appropriateForURL:nil
                                                             create:NO
                                                              error:nil];
    NSLog(@"File Url : %@", dirURL.absoluteString);
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:dirURL.absoluteString];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (NSString *)pathForURL:(NSString *)urlString
{
    NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                 inDomain:NSUserDomainMask
                                                        appropriateForURL:nil
                                                                   create:NO
                                                                    error:nil];
    NSURL *cafURL = [documentsURL URLByAppendingPathComponent:urlString];
    return cafURL.absoluteString;
}
- (void)UnZip:(CDVInvokedUrlCommand*)command {
    [self.commandDelegate runInBackground:^{
        CDVPluginResult* pluginResult = nil;
        @try {
            NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
            NSError *error;
            //NSString *zipPath = [self pathForURL:zipURL];
            //NSString *destinationPath = [self pathForURL:destinationURL];
            NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
            NSString *zipPath = [dir stringByAppendingPathComponent: dict[@"filePath"]];
            NSString *destinationPath = [dir stringByAppendingPathComponent: dict[@"destination"]];
            
            if([SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath overwrite:YES password:nil error:&error delegate:self]) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            } else {
                NSLog(@"%@ - %@", @"Error occurred during unzipping", [error localizedDescription]);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Error occurred during unzipping"];
            }
        } @catch(NSException* exception) {
            NSLog(@"%@ - %@", @"Error occurred during unzipping", [exception debugDescription]);
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Error occurred during unzipping"];
        }
        
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

-(void)DownloadFile:(CDVInvokedUrlCommand*)command {
    self.callbackIdForImagePicker = command.callbackId;
    NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *downloadPath = [dir stringByAppendingPathComponent: dict[@"filePath"]];
    NSString *filePath = [downloadPath stringByAppendingPathComponent:[dict[@"filePath"] lastPathComponent]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dict[@"url"]]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to download the file."];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
        }
        if (data) {
            [data writeToFile:filePath atomically:YES];
            CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
            [self.commandDelegate sendPluginResult:result callbackId:self.callbackIdForImagePicker];
        }
    }];
}

- (void)OpenFileWithViewer:(CDVInvokedUrlCommand *)command {
    self.fileOpenCallbackId = command.callbackId;
    [self.commandDelegate runInBackground:^{
        CDVPluginResult* commandResult = nil;
        NSString *filePath = [self pathForURL:[command.arguments objectAtIndex:0]];
        if (filePath != nil && [filePath length] > 0) {
            NSURL *url = [NSURL URLWithString:filePath];
            NSError *err;
            if (url.isFileURL && [url checkResourceIsReachableAndReturnError:&err] == YES) {
                self.fileUrl = url;
                QLPreviewController *previewCtrl = [[QLPreviewController alloc] init];
                previewCtrl.delegate = self;
                previewCtrl.dataSource = self;
                [previewCtrl.navigationItem setRightBarButtonItem:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.viewController presentViewController:previewCtrl animated:YES completion:nil];
                });
                commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Success"];
                [commandResult setKeepCallback:[NSNumber numberWithBool:YES]];
            } else {
                NSLog(@"Invalid file URL");
                commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid file URL"];
            }
        } else {
            NSLog(@"Missing URL argument");
            commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Missing URL argument"];
        }
        [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
    }];
}

#pragma - QLPreviewControllerDataSource Protocol

- (NSInteger)numberOfPreviewItemsInPreviewController:
(QLPreviewController *)controller {
    return 1;
}

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller
                    previewItemAtIndex:(NSInteger)index {
    return self;
}

- (void)previewControllerDidDismiss:(QLPreviewController *)controller {
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"resume"];
    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.fileOpenCallbackId];
    self.fileOpenCallbackId = nil;
}

#pragma - QLPreviewItem Protocol

- (NSURL *)previewItemURL {
    return self.fileUrl;
}
@end
