//
//  AppUtils.m
//
//
//  Created by EbitM07 on 12/26/16.
//  Copyright © 2016 EbitM07. All rights reserved.
//

#import "AppUtils.h"

#define	MASK	0X3FFFFFFF

static NSArray *aryCategory = nil;
NSData *dataX_Key16;
NSData *dataY_Key16;
NSData *dataZ_Key16;
NSData *dataK_Key16;

@implementation AppUtils
//@synthesize dic_Response;
//@synthesize m_Status;
//@synthesize m_strPostMsg;

+(NSArray *)aryCategory {
    NSDictionary *dic = [AppUtils getCampSvrConf];
    if (dic != nil) {
        aryCategory = dic[@"hoCatagories"];
    } else {
        if (aryCategory == nil) {
            aryCategory = @[@"Coffee & Chill", @"Lunch/Dinner", @"Workout", @"Sports/Activities", @"Study", @"Party", @"Shopping", @"Rideshare", @"Go for a walk", @"Other"];
        }
    }
    return aryCategory;
}

+(NSData *)dataX_Key16 {
    if (dataX_Key16 == nil) {
        // init data x Key
        NSMutableData *dataX = [[NSMutableData alloc] init];
        DataPacketManager *dpm = [[DataPacketManager alloc] init];
        NSData *dataX0 = [dpm convertHexStringToNSData: @"3C96CA3C63A5639C"];
        NSData *dataX1 = [dpm convertHexStringToNSData: @"63A3A5639C66C3C9"];
        [dataX appendData:dataX0];
        [dataX appendData:dataX1];
        dataX_Key16 = dataX.copy;
    }
    return dataX_Key16;
}

+(NSData *)dataY_Key16 {
    if (dataY_Key16 == nil) {
        // init data y Key
        NSMutableData *dataY = [[NSMutableData alloc] init];
        DataPacketManager *dpm = [[DataPacketManager alloc] init];
        NSData *dataY0 = [dpm convertHexStringToNSData: @"35C99A66C59A653A"];
        NSData *dataY1 = [dpm convertHexStringToNSData: @"635C9A3A59659A6C"];
        [dataY appendData:dataY0];
        [dataY appendData:dataY1];
        dataY_Key16 = dataY.copy;
    }
    return dataY_Key16;
}

+(NSData *)dataZ_Key16 {
    if (dataZ_Key16 == nil) {
        // init data z Key
        NSMutableData *dataZ = [[NSMutableData alloc] init];
        DataPacketManager *dpm = [[DataPacketManager alloc] init];
        NSData *dataZ0 = [dpm convertHexStringToNSData: @"539C6A536C9A59A5"];
        NSData *dataZ1 = [dpm convertHexStringToNSData: @"3A595C36C356A9A5"];
        [dataZ appendData:dataZ0];
        [dataZ appendData:dataZ1];
        dataZ_Key16 = dataZ.copy;
    }
    return dataZ_Key16;
}

+(NSData *)dataK_Key16 {
    if (dataK_Key16 == nil) {
        // init data k Key
        NSMutableData *dataK = [[NSMutableData alloc] init];
        DataPacketManager *dpm = [[DataPacketManager alloc] init];
        NSData *dataK0 = [dpm convertHexStringToNSData: @"74B836D5CF10E29A"];
        NSData *dataK1 = [dpm convertHexStringToNSData: @"5B291CF047A6D38E"];
        [dataK appendData:dataK0];
        [dataK appendData:dataK1];
        dataK_Key16 = dataK.copy;
    }
    return dataK_Key16;
}

+(NSString *)getJsonFormatedStringFromDictionary:(NSDictionary *)dicData {
    NSError *err;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&err];
    NSString * strJson = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
    return strJson;
}

+(void)postUrlCall:(NSString *)strURL Parameter:(NSDictionary *)dicParameter handler:(void (^)(BOOL, NSDictionary *, NSString *))finishBlock {
    /*
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html", nil];
    //[serializer setValue:@"key=AIzaSyBLQpuNvV3-8FS7b1dQaaYTRGY4iHlJZoI" forHTTPHeaderField:@"Authorization"];
    
    [manager POST:strURL parameters:dicParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"Dic %@", responseObject);
        
        NSDictionary *dic_Response;
        dic_Response = (NSDictionary *)responseObject;
        finishBlock(true, dic_Response, @"Success");
    } failure:
     ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"Error: %@",error);
         finishBlock(false, nil, error.localizedDescription);
     }];
    */
    
    //create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    //Set Params
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    
    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"application/json;"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // post body
    NSMutableData *body = [NSMutableData data];
    // setting the body of the post to the request
    [request setHTTPBody:body];
    
    // set URL
    [request setURL:[NSURL URLWithString:strURL]];
    
    //NSURLSession *urlSession = [[NSURLSession alloc] init];
    NSURLSession *urlSession = [NSURLSession sharedSession];
    [[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error == nil) {
            // Response
            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
            if ([httpResponse statusCode] == 200) {
                
                // Parse JSON
                NSError* error;
                NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:kNilOptions
                                                                       error:&error];
                if (error == nil) {
                    finishBlock(true, json, @"Success");
                } else {
                    finishBlock(false, nil, @"Response JSON Parsing Error");
                }
            } else {
                finishBlock(false, nil, [NSString stringWithFormat:@"http status code: %ld",(long)[httpResponse statusCode]]);
            }
        } else {
            // Error
            finishBlock(false, nil, error.localizedDescription);
        }
    }] resume];
}

+(void)getUrlCall:(NSString *)strURL Parameter:(NSDictionary *)dicParameter handler:(void (^)(BOOL, NSDictionary *, NSString *))finishBlock {
    /*
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //[serializer setValue:@"key=AIzaSyBLQpuNvV3-8FS7b1dQaaYTRGY4iHlJZoI" forHTTPHeaderField:@"Authorization"];
    
    manager.requestSerializer = serializer;
    
    NSLog(@"parm %@",dicParameter);
    NSLog(@"Url %@",strURL);
    
    [manager GET:strURL parameters:dicParameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"Dic %@", responseObject);
        
        NSDictionary *dic_Response;
        dic_Response = (NSDictionary *)responseObject;
        finishBlock(true, dic_Response, @"Success");
    } failure:
     ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"Error: %@",error);
         finishBlock(false, nil, error.localizedDescription);
     }];
    */
    
    //create request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    //Set Params
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:60];
    [request setHTTPMethod:@"GET"];
    
    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"application/json;"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // set URL
    [request setURL:[NSURL URLWithString:strURL]];
    
    NSURLSession *urlSession = [NSURLSession sharedSession];
    
    [[urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error == nil) {
            // Response
            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
            if ([httpResponse statusCode] == 200) {
                
                // Parse JSON
                NSError* error;
                NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:kNilOptions
                                                                       error:&error];
                if (error == nil) {
                    finishBlock(true, json, @"Success");
                } else {
                    finishBlock(false, nil, @"Response JSON Parsing Error");
                }
            } else {
                finishBlock(false, nil, [NSString stringWithFormat:@"http status code: %ld",(long)[httpResponse statusCode]]);
            }
        } else {
            // Error
            finishBlock(false, nil, error.localizedDescription);
        }
    }] resume];
}

+(NSString *)convertNSDateToString:(NSDate *)date Format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormatter setDateFormat:format];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}

+(NSDate *)convertStringToNSDate:(NSString *)strDate Format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormatter setDateFormat:format];
    //[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    return [dateFormatter dateFromString:strDate];
}

+(void)ShowAlert:(NSString *) message FromVC:(UIViewController*)selfVC Completion: (void (^)(UIAlertAction *)) callbackBlock
 {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Friends On Campus" message:message preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:callbackBlock];
     [alert addAction:action];
     [selfVC presentViewController:alert animated:true completion:nil];
}

+(NSString *)GetEmail {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDEMAIL"];
}

+(void)SetEmail:(NSString *)email {
    [[NSUserDefaults standardUserDefaults]setValue:email forKey:@"SAVEDEMAIL"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetPassword {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDPASSWORD"];
}

+(void)SetPassword:(NSString *)password {
    [[NSUserDefaults standardUserDefaults]setValue:password forKey:@"SAVEDPASSWORD"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetUserId {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDUSERID"];
}

+(void)SetUserId:(NSString *)userId {
    [[NSUserDefaults standardUserDefaults]setValue:userId forKey:@"SAVEDUSERID"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetCampusd {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDCAMPUSID"];
}

+(void)SetCampusId:(NSString *)campusId {
    [[NSUserDefaults standardUserDefaults]setValue:campusId forKey:@"SAVEDCAMPUSID"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}


+(NSString *)GetCampSrvIp {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDCAMPSRVIP"];
}

+(void)SetCampSrvIp:(NSString *)campSrvIp {
    [[NSUserDefaults standardUserDefaults]setValue:campSrvIp forKey:@"SAVEDCAMPSRVIP"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetCampSrvPort {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDCAMPSRVPORT"];
}

+(void)SetCampSrvPort:(NSString *)campSrvPort {
    [[NSUserDefaults standardUserDefaults]setValue:campSrvPort forKey:@"SAVEDCAMPSRVPORT"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetPhase {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVEDPHASE"];
}

+(void)SetPhase:(NSString *)phase {
    [[NSUserDefaults standardUserDefaults]setValue:phase forKey:@"SAVEDPHASE"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetAutoLoginStatus {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"ISAUTOLOGIN"];
}

+(void)SetAutoLoginStatus:(NSString *)status {
    [[NSUserDefaults standardUserDefaults]setValue:status forKey:@"ISAUTOLOGIN"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)GetIsLoggedIn {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"ISLOGGEDIN"];
}

+(void)SetIsLoggedIn:(NSString *)status {
    [[NSUserDefaults standardUserDefaults]setValue:status forKey:@"ISLOGGEDIN"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)getGCMID {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"GCM_ID"];
}

+(void)SetGCMID:(NSString *)gcmid {
    [[NSUserDefaults standardUserDefaults]setValue:gcmid forKey:@"GCM_ID"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)getSchoolCampus {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SCHOOL_CAMPUS"];
}

+(void)SetSchoolCampus:(NSString *)schoolCampus {
    [[NSUserDefaults standardUserDefaults]setValue:schoolCampus forKey:@"SCHOOL_CAMPUS"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(UserPrivacy *)getUserPrivacySetting {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [prefs objectForKey:@"UserPrivacy"];
    UserPrivacy * userPrivacy = [NSKeyedUnarchiver unarchiveObjectWithData:myEncodedObject];
    return userPrivacy;
}

+(void)saveUserPrivacySetting:(UserPrivacy *)object {
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"UserPrivacy"];
    [prefs synchronize];
}

+(UserNotification *)getUserNotificationSetting {
    UserNotification * userPrivacy = [[UserNotification alloc] init];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    userPrivacy.reqFriend = [prefs boolForKey:@"reqFriend"];
    userPrivacy.hangOutJoin = [prefs boolForKey:@"hangOutJoin"];
    userPrivacy.hangOutChange = [prefs boolForKey:@"hangOutChange"];
    userPrivacy.onCampus = [prefs objectForKey:@"onCampus"];
    userPrivacy.hangOutCreate = [prefs objectForKey:@"hangOutCreate"];
    userPrivacy.v = [prefs objectForKey:@"userNotificationVersion"];
    
    return userPrivacy;
}

+(void)saveUserNotificationSetting:(UserNotification *)object {
    [[NSUserDefaults standardUserDefaults]setBool: object.reqFriend forKey:@"reqFriend"];
    [[NSUserDefaults standardUserDefaults]setBool: object.hangOutJoin forKey:@"hangOutJoin"];
    [[NSUserDefaults standardUserDefaults]setBool: object.hangOutChange forKey:@"hangOutChange"];
    [[NSUserDefaults standardUserDefaults]setValue:object.onCampus forKey:@"onCampus"];
    [[NSUserDefaults standardUserDefaults]setValue:object.hangOutCreate forKey:@"hangOutCreate"];
    [[NSUserDefaults standardUserDefaults]setValue:object.v forKey:@"userNotificationVersion"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)getSelectedCategory {
    return [[NSUserDefaults standardUserDefaults] valueForKey:@"SELECTED_CATEGORY"];
}

+(void)SetSelectedCategory:(NSString *)selectedCategory {
    [[NSUserDefaults standardUserDefaults]setValue:selectedCategory forKey:@"SELECTED_CATEGORY"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(BOOL)GetOnCampusSharing {
    return [[NSUserDefaults standardUserDefaults]boolForKey:@"ONCAMPUS_SHARING"];
}

+(void)SetOnCampusSharing:(BOOL)status {
    [[NSUserDefaults standardUserDefaults]setBool:status forKey:@"ONCAMPUS_SHARING"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(BOOL)GetShowPublicHangout {
    return [[NSUserDefaults standardUserDefaults]boolForKey:@"SHOW_PUBLIC_HANGOUT"];
}

+(void)SetShowPublicHangout:(BOOL)show {
    [[NSUserDefaults standardUserDefaults]setBool:show forKey:@"SHOW_PUBLIC_HANGOUT"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(BOOL)GetIsInGeofence {
    return [[NSUserDefaults standardUserDefaults]boolForKey:@"IS_IN_GEOFENCE"];
}

+(void)SetIsInGeofence:(BOOL)isInGeofence {
    [[NSUserDefaults standardUserDefaults]setBool:isInGeofence forKey:@"IS_IN_GEOFENCE"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)getGlobalVersion {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"GLOBAL_VERSION"];
}

+(void)SetGlobalVersion:(NSString *)globalVersion {
    [[NSUserDefaults standardUserDefaults]setValue:globalVersion forKey:@"GLOBAL_VERSION"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSDictionary *)getCampSvrConf {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"CAMP_SVR_CONF"];
}

+(void)SetCampSvrConf:(NSDictionary *)dicData {
    [[NSUserDefaults standardUserDefaults]setValue:dicData forKey:@"CAMP_SVR_CONF"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(NSString *)getInterstitialAdHour {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"INTERSTITIAL_AD_HOUR"];
}

+(void)setInterstitialAdHour:(NSString *)hour {
    [[NSUserDefaults standardUserDefaults]setValue:hour forKey:@"INTERSTITIAL_AD_HOUR"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

+(BOOL)getDisplayAd {
    return [[NSUserDefaults standardUserDefaults]boolForKey:@"DISPLAY_AD"];
}

+(void)SetDisplayAd:(BOOL)display {
    [[NSUserDefaults standardUserDefaults]setBool:display forKey:@"DISPLAY_AD"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}



+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate {
    
    NSDateComponents *components;
    NSInteger year;
    NSInteger month;
    NSInteger days;
    NSInteger hour;
    NSInteger minutes;
    NSInteger seconds;
    NSString *durationString;
    
    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
                                                 fromDate: startDate toDate: endDate options: 0];
    year = [components year];
    month = [components month];
    days = [components day];
    hour = [components hour];
    minutes = [components minute];
    seconds = [components second];
    
    //    if (year > 0) {
    //
    //        if (year > 1) {
    //            durationString = [NSString stringWithFormat:@"%ld years ago", (long)year];
    //        }
    //        else {
    //            durationString = [NSString stringWithFormat:@"%ld year ago", (long)year];
    //        }
    //        return durationString;
    //    }
    
    //    if (month > 0) {
    //
    //        if (month > 1) {
    //            durationString = [NSString stringWithFormat:@"%ld months ago", (long)month];
    //        }
    //        else {
    //            durationString = [NSString stringWithFormat:@"%ld month ago", (long)month];
    //        }
    //        return durationString;
    //    }
    
    if (days > 0) {
        
        if (days > 1) {
            durationString = [NSString stringWithFormat:@"%ld d", (long)days];
        }
        else {
            durationString = [NSString stringWithFormat:@"%ld d", (long)days];
        }
        return durationString;
    }
    
    if (hour > 0) {
        
        if (hour > 1) {
            durationString = [NSString stringWithFormat:@"%ld h", (long)hour];
        }
        else {
            durationString = [NSString stringWithFormat:@"%ld h", (long)hour];
        }
        return durationString;
    }
    
    if (minutes > 0) {
        
        if (minutes > 1) {
            durationString = [NSString stringWithFormat:@"%ld m", (long)minutes];
        }
        else {
            durationString = [NSString stringWithFormat:@"%ld m", (long)minutes];
        }
        return durationString;
    }
    
    //    if (seconds > 0) {
    //
    //        if (seconds > 1) {
    //            durationString = [NSString stringWithFormat:@"%ld seconds ago", (long)seconds];
    //        }
    //        else {
    //            durationString = [NSString stringWithFormat:@"%ld second ago", (long)seconds];
    //        }
    //        return durationString;
    //    }
    
    return @"";
}


+(NSData *) XORBytesWithData1:(NSData *) data1 Data2:(NSData *)data2 {
    const char *data1Bytes = [data1 bytes];
    const char *data2Bytes = [data2 bytes];
    // Mutable data that individual xor'd bytes will be added to
    NSMutableData *xorData = [[NSMutableData alloc] init];
    for (int i = 0; i < data1.length; i++){
        const char xorByte = data1Bytes[i] ^ data2Bytes[i];
        [xorData appendBytes:&xorByte length:1];
    }
    return xorData;
}

+(BOOL) IsValidEmail:(NSString *)checkString {    
    BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
    
    /*
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:checkString];
    */
}

//to scale images without changing aspect ratio
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
    
    float width = newSize.width;
    float height = newSize.height;
    
    UIGraphicsBeginImageContext(newSize);
    CGRect rect = CGRectMake(0, 0, width, height);
    
    float widthRatio = image.size.width / width;
    float heightRatio = image.size.height / height;
    float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;
    
    width = image.size.width / divisor;
    height = image.size.height / divisor;
    
    rect.size.width  = width;
    rect.size.height = height;
    
    //indent in case of width or height difference
    float offset = (width - height) / 2;
    if (offset > 0) {
        rect.origin.y = offset;
    }
    else {
        rect.origin.x = -offset;
    }
    
    [image drawInRect: rect];
    
    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return smallImage;
}

+ (CGFloat)getLabelHeight:(UILabel*)label {
    CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    CGSize size;
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:label.font}
                                                  context:context].size;
    
    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
    
    return size.height;
}

+ (int) convertToNewDateFormate:(NSDate *)date {
    //yyMMddHHmm
    NSString *strYY = [self convertNSDateToString:date Format:@"yyyy"];
    int intYY = [strYY intValue] - 0;
    strYY = [NSString stringWithFormat:@"%d", intYY];
    strYY = [strYY substringFromIndex:2];
    //intYY = [strYY intValue];
    NSString *str = [self convertNSDateToString:date Format:@"MMddHHmm"];
    NSString *strFinal = [NSString stringWithFormat:@"%@%@", strYY, str];
    return [strFinal intValue];
}

+ (NSDate *) convertFromNewDateFormate:(int)intDate {
    //yyMMddHHmm
    NSString *strParaDate = [NSString stringWithFormat:@"%d", intDate];
    NSString *strYY = [strParaDate substringToIndex:2];
    NSString *str = [strParaDate substringFromIndex:2];
    int intYY = [strYY intValue] + 0;
    NSString *strFinal = [NSString stringWithFormat:@"%d%@", intYY, str];
    NSDate *date = [self convertStringToNSDate:strFinal Format:@"yyMMddHHmm"];
    
    return date;
}

+ (void) displayInterstitialAd {
    NSDictionary *dicData = [AppUtils getCampSvrConf];
    Ad *ad = [[Ad alloc] initWithDictionary:dicData[@"ad"]];
    int second = 60; //[ad.hour intValue] * 60 * 60;
    if (ad.showAd) {        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        if (appDelegate.dtLastAdLoadTime != nil) {
            int diff = [[NSDate date] timeIntervalSinceDate: appDelegate.dtLastAdLoadTime];
            if (diff >= second) {
                [appDelegate displayInterstitialAD];
            }
        } else {
            [appDelegate displayInterstitialAD];
        }
    }
}

+(void)sendScreenTracker:(NSString *)screenName {
    id<GAITracker> tracker = [GAI sharedInstance].defaultTracker;
    [tracker set:kGAIScreenName value: screenName];
    [tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}

+(void)sendEventTrackerWithAction:(NSString *)action {
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    
    [tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"iOS"
                                                          action:action
                                                           label:@""
                                                           value:nil] build]];
}

#pragma mark
#pragma mark Hash functions


+(int)getHashString:(NSString *)data {
    if (data == 0) return 0;
    
    int len = data.length;
    if (len > 32) len=32;
    
    int hv = 0;
    for (int i = 0; i < len; i++) {
        hv += (i + 1) * ([data characterAtIndex:i] & 0xFF);
        if (hv > MASK)
            hv &= MASK;
    }
    return hv;
}

+(int)getHashInt:(int) data {
    return data & 0xFFFF;
}

+(int)getHashBool:(int) data {
    return data & 0x01;
}

+(float)trimDoubleAfterDecimalPoint:(int)floatingDigit DoubleValue:(double)value {
    double dbl = value;
    NSString *strValue = [[NSNumber numberWithDouble:dbl] stringValue];
    
    NSRange range = [strValue rangeOfString:@"."];
    if (range.location != NSNotFound) {
        NSString *newString;
        if (strValue.length >= range.location + (floatingDigit + 1)) {
            newString = [strValue substringWithRange:NSMakeRange(0, range.location + (floatingDigit + 1))];
        } else {
            newString = strValue;
        }
        dbl = [newString floatValue];
    } else {
        NSLog(@" Dot(.) not found");
    }
    return dbl;
}

+(void)displayLocalNotification:(NSString *)strAlertBody {
    
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
            // Notifications not allowed
            NSLog(@"Local Notifications not allowed");
        } else {
            UNMutableNotificationContent *content = [UNMutableNotificationContent new];
            content.title = @"Friends On Campus";
            //content.subtitle = @"sub title";
            content.body = strAlertBody;
            content.sound = [UNNotificationSound defaultSound];
            
            // fire notification
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
            NSString *identifier = @"UYLLocalNotification";
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger: trigger];
            
            [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                if (error != nil) {
                    NSLog(@"Something went wrong: %@",error);
                }
            }];
        }
    }];
    
#else
    
    // create a corresponding local notification
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = strAlertBody; // text that will be displayed in the notification
    
    //notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view"
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];//date (when notification will be fired)
    notification.soundName = UILocalNotificationDefaultSoundName; // play default sound
    notification.alertAction = @"View";
    //notification.userInfo = ["title": item.title, "UUID": item.UUID] // assign a unique identifier to the notification so that we can retrieve it later
    [[UIApplication sharedApplication] scheduleLocalNotification: notification];
    
#endif
}

@end
