#import "mInterface.h"
#import "XMLConverter.h"
#import "InternetConnection.h"
#import <AssetsLibrary/AssetsLibrary.h>

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

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

#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];
    } @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];
    }
}

-(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 {
            NSMutableDictionary * dict = [[command arguments] objectAtIndex:0];
            NSString* directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
            NSString *fromPath = dict[@"srcPath"];
            NSString *toPath = [NSString stringWithFormat:@"%@/%@", directory, dict[@"desPath"]];
            // Check if destination folder is exists
            if (![[NSFileManager defaultManager] fileExistsAtPath:toPath]){
                // Create folder if not exists
                [[NSFileManager defaultManager] createDirectoryAtPath:toPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            NSString *destFilePath = [NSString stringWithFormat:@"%@/%@", toPath, dict[@"desFile"]];
            NSError *error;
            //Check file already exists or not
            if([[NSFileManager defaultManager] fileExistsAtPath:fromPath])
            {
                if(![[NSFileManager defaultManager] fileExistsAtPath:destFilePath]){
                    if([[NSFileManager defaultManager] copyItemAtPath:fromPath toPath:destFilePath error:&error]==YES)
                    {
                        NSLog(@"File copied..");
                    }
                }
                CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
            } else {
                CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                [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 {
        BOOL isEnabled = false;
        NSString* directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                  NSUserDomainMask, YES)[0];
        NSString *queueMgr = [NSString stringWithFormat:@"%@/%@/database/user_profile.txt", directory,[self GetAppName]];
        NSString *queuePath = [NSString stringWithFormat:@"%@/%@/database/queue", directory,[self GetAppName]];
        NSString *contents =[NSString stringWithContentsOfFile:queueMgr encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [contents dataUsingEncoding:NSUTF8StringEncoding];
        long imgSize = data.length;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *holeFileList = [fileManager contentsOfDirectoryAtPath:queuePath error:nil];
        NSMutableArray *fileList = [holeFileList mutableCopy];
        if ([fileList containsObject:@".DS_Store"]) {
            [fileList removeObject:@".DS_Store"];
        }
        if ((fileList == nil || [fileList count] == 0) || imgSize == 0) {
            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(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]){
            // Create folder if not exists
            [[NSFileManager defaultManager] createDirectoryAtPath:dest withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *destination = [NSString stringWithFormat:@"%@/%@", dest, [imageRep filename]];
        UIImage *img = ivPickedImage.image;
        NSData * data = UIImagePNGRepresentation(img);
        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 forKey:@"filePath"];
        [dict setValue:[imageRep filename] 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];
}

-(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 SpinnerHide];
    }
    [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];
    NSString *comapareString = dict[@"show"];
    if([comapareString isEqualToString:@"true"]){
        spinnerCallbackId = command.callbackId;
        
        //If there is a loading mask yet we hide it
        [self SpinnerHide];
        UIViewController *rootViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        
        [rootViewController.view addSubview:self.overlay];
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    } else {
        [self SpinnerHide];
    }
}

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

#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
