//
//  Utilities.m
//  Verif-y
//
//  Created by MTN on 17/09/20.
//

#import "Utilities.h"
#import "Reachability.h"

#define FontSize ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 15 : 12)

@implementation Utilities

/**
    Check availability of internet.
 */
+ (BOOL)checkInternetConnection {
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return !(networkStatus == NotReachable);
}

/**
    Trimming of white space from string.
 */
+ (BOOL)checkWhiteSpaces:(NSString *)aStr {

    NSString *probablyEmpty = [aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (![probablyEmpty isEqualToString:@""] && probablyEmpty)
        return YES;
    else
        return NO;
}

+ (NSString *)encodeToBase64String:(UIImage *)image {
    if(image != nil){
        return [UIImageJPEGRepresentation(image, 0) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    } else {
        return nil;
    }
}

+ (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

+ (NSString*)encodeStringTo64:(NSString*)fromString {
    NSData *plainData = [fromString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [plainData base64EncodedStringWithOptions:kNilOptions];
    return base64String;
}

+ (NSData *)compressForUpload:(UIImage *)originalImg {
    //UIImage  *original = [UIImage imageWithData:originalImg];
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize = 250*1024;
    NSData *imageData = UIImageJPEGRepresentation(originalImg, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(originalImg, compression);
    }
    return imageData;
}

+ (NSString *) compressPNGBase64:(UIImage *) img {
    //UIImage *changeSize = [self imageWithImage:img scaledToSize:CGSizeMake(120, 90)];
    //NSData *imageData = UIImagePNGRepresentation(changeSize);
    NSData *imageData = UIImagePNGRepresentation(img);
    NSString *base64String = [imageData base64EncodedStringWithOptions:0];
    return base64String;
}

+ (void) customTitleImage: (UINavigationItem*) navigationItem Logo:(NSString*) base64 {
    UIImage *image;
    if([base64 length]>0){
        image = [self decodeBase64ToImage:base64];
    } else {
        return;
    }
    //UIImage *image = [UIImage imageNamed:@"logo.png"];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.translatesAutoresizingMaskIntoConstraints = false;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.image = image;
    [imageView.heightAnchor constraintEqualToConstant:35].active = YES;
   
    UIView *contentView = [[UIView alloc] init];
    navigationItem.titleView = contentView;
    [navigationItem.titleView addSubview:imageView];
    [imageView.centerXAnchor constraintEqualToAnchor:contentView.centerXAnchor].active = true;
    [imageView.centerYAnchor constraintEqualToAnchor:contentView.centerYAnchor].active = true;
}

+ (void) customTitleText:(UINavigationItem *)navigationItem TitleText:(NSString *)titleText FontColor:(NSString*)fontColor {
    if([titleText length] <= 0){
        return;
    }
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.text = titleText;
    titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:17.0f];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.numberOfLines = 2;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [self colorFromColorString:fontColor];
    [titleLabel sizeToFit];
    navigationItem.titleView = titleLabel;
}

+ (NSString*) setOSLanguage:(NSString*) language {
    //pt-BR Portuguese-Brazil //de German //ja - Japan //ar - arabic //it- Italian //zh-Hans - Chinese simplified //zh-Hant - Chinese traditional
    NSString *theString;
    NSString *setLanguage = @"en";
    if(!([language isEqualToString:@"pt-PT"] || [language isEqualToString:@"pt-BR"])){
        theString = [self extractLanguage:language];
    } else {
        theString = language;
    }
    NSArray *items = @[@"en", @"es", @"it", @"pt-PT", @"pt-BR", @"fr", @"de",@"ja", @"zh-Hans", @"zh-Hant", @"hi", @"ar"];
    int item = (int)[items indexOfObject:theString];
    switch (item) {
        case 0:
            //English
           setLanguage = theString;
           break;
        case 1:
           //spanish
           setLanguage = theString;
           break;
        case 2:
           //italian
           setLanguage = theString;
           break;
        case 3:
           //Portuguese
           setLanguage = theString;
           break;
        case 4:
           //Portuguese brazil
           setLanguage = theString;
           break;
        case 5:
           //French
           setLanguage = theString;
           break;
        case 6:
           //German
           setLanguage = theString;
           break;
        case 7:
           //Japanese
           setLanguage = theString;
           break;
        case 8:
           //Chines simplifield
           setLanguage = theString;
           break;
        case 9:
           //Chinese Traditional
           setLanguage = theString;
           break;
        case 10:
           //Hindi
           setLanguage = theString;
           break;
        case 11:
           //Arabic
           setLanguage = theString;
           break;
        default:
           //Default english
           setLanguage = @"en";
           break;
    }
    return setLanguage;
}

+ (NSString*) getGeoLanguage:(NSString*) countryName {
    NSString *theString;
    NSString *setLanguage = @"en";
    
    if([countryName length]>0) {
        theString = [countryName lowercaseString];
    } else {
        return nil;
    }
    NSArray *languages = @[@"en", @"es", @"it", @"pt-PT", @"pt-BR", @"fr", @"de",@"ja", @"zh-Hans", @"zh-Hant", @"hi", @"ar"];
    NSArray *items = @[@"united states", @"spain", @"italy", @"Portugal", @"brazil", @"france", @"germany",@"japan", @"china", @"india", @"saudi arabia"];
    int item = (int)[items indexOfObject:theString];
    switch (item) {
        case 0:
            //English
           setLanguage = [languages objectAtIndex:0];
           break;
        case 1:
           //spanish
           setLanguage = [languages objectAtIndex:1];
           break;
        case 2:
           //italian
           setLanguage = [languages objectAtIndex:2];
           break;
        case 3:
           //Portuguese
           setLanguage = [languages objectAtIndex:3];
           break;
        case 4:
           //Portuguese brazil
           setLanguage = [languages objectAtIndex:4];
           break;
        case 5:
           //French
           setLanguage = [languages objectAtIndex:5];
           break;
        case 6:
           //German
           setLanguage = [languages objectAtIndex:6];
           break;
        case 7:
           //Japanese
           setLanguage = [languages objectAtIndex:7];
           break;
        case 8:
           //Chines simplifield
           setLanguage = [languages objectAtIndex:8];
           break;
        case 9:
            //Chinese Traditional
            setLanguage = theString;
            break;
        case 10:
           //Hindi
           setLanguage = [languages objectAtIndex:9];
           break;
        case 11:
           //Arabic
           setLanguage = [languages objectAtIndex:11];
           break;
        default:
           //Default english
           setLanguage = @"en";
           break;
    }
    return setLanguage;
}

+ (NSString*) getLanguageString:(NSString*) Language {
    NSString *theString;
    NSString *setLanguage = @"english";
    
    if([Language length]>0) {
        theString = Language;
    } else {
        return nil;
    }
    NSArray *languages = @[@"english", @"spanish", @"italian", @"portuguese", @"brazil", @"french", @"german",@"japanese", @"chinese-simplified", @"chinese-traditional", @"hindi", @"arabic"];
    
    NSArray *items = @[@"en", @"es", @"it", @"pt-PT", @"pt-BR", @"fr", @"de",@"ja", @"zh-Hans", @"zh-Hant", @"hi", @"ar"];
    int item = (int)[items indexOfObject:theString];
    switch (item) {
        case 0:
            //English
           setLanguage = [languages objectAtIndex:0];
           break;
        case 1:
           //spanish
           setLanguage = [languages objectAtIndex:1];
           break;
        case 2:
           //italian
           setLanguage = [languages objectAtIndex:2];
           break;
        case 3:
           //Portuguese
           setLanguage = [languages objectAtIndex:3];
           break;
        case 4:
           //Portuguese brazil
           setLanguage = [languages objectAtIndex:4];
           break;
        case 5:
           //French
           setLanguage = [languages objectAtIndex:5];
           break;
        case 6:
           //German
           setLanguage = [languages objectAtIndex:6];
           break;
        case 7:
           //Japanese
           setLanguage = [languages objectAtIndex:7];
           break;
        case 8:
           //Chines simplifield
           setLanguage = [languages objectAtIndex:8];
           break;
        case 9:
            //Chinese Traditional
            setLanguage = [languages objectAtIndex:9];
            break;
        case 10:
           //Hindi
           setLanguage = [languages objectAtIndex:10];
           break;
        case 11:
           //Arabic
           setLanguage = [languages objectAtIndex:11];
           break;
        default:
           //Default english
           setLanguage = @"english";
           break;
    }
    return setLanguage;
}

+ (NSString*) checkLanguageSupported:(NSString*) language {
    NSString *theString;
    NSString *setLanguage = @"en";
    
    if([language length]>0) {
        theString = [language lowercaseString];
    } else {
        return nil;
    }
    NSArray *languages = @[@"en", @"es", @"it", @"pt-PT", @"pt-BR", @"fr", @"de",@"ja", @"zh-Hans", @"zh-Hant", @"hi", @"ar"];
    //NSArray *items = @[@"en", @"es", @"it", @"pt-pt", @"pt-br", @"fr", @"de",@"ja", @"zh-hans", @"zh-hant", @"hi", @"ar"];
    NSArray *items = @[@"en", @"es", @"it", @"pt", @"br", @"fr", @"de",@"ja", @"cn", @"tw", @"hi", @"ar"];
    int item = (int)[items indexOfObject:theString];
    switch (item) {
        case 0:
            //English
           setLanguage = [languages objectAtIndex:0];
           break;
        case 1:
           //spanish
           setLanguage = [languages objectAtIndex:1];
           break;
        case 2:
           //italian
           setLanguage = [languages objectAtIndex:2];
           break;
        case 3:
           //Portuguese
           setLanguage = [languages objectAtIndex:3];
           break;
        case 4:
           //Portuguese brazil
           setLanguage = [languages objectAtIndex:4];
           break;
        case 5:
           //French
           setLanguage = [languages objectAtIndex:5];
           break;
        case 6:
           //German
           setLanguage = [languages objectAtIndex:6];
           break;
        case 7:
           //Japanese
           setLanguage = [languages objectAtIndex:7];
           break;
        case 8:
           //Chinese simplifield
           setLanguage = [languages objectAtIndex:8];
           break;
        case 9:
           //Chinese traditional
           setLanguage = [languages objectAtIndex:9];
           break;
        case 10:
           //Hindi
           setLanguage = [languages objectAtIndex:10];
           break;
        case 11:
            //Arabic
           setLanguage = [languages objectAtIndex:11];
           break;
        default:
           //Default english
           setLanguage = @"en";
           break;
    }
    return setLanguage;
}

+ (NSString*) extractLanguage:(NSString*) language {
    // Format is Lang - Region
    NSString *fullString = [[NSLocale preferredLanguages] firstObject];
    NSMutableArray *langAndRegion = [NSMutableArray arrayWithArray:[fullString componentsSeparatedByString:@"-"]];
    // Region is the last item //NSString *region = [langAndRegion objectAtIndex:langAndRegion.count - 1];
    // Remove region
    [langAndRegion removeLastObject];
    // We recreate array with the lang
    NSString *lang = [langAndRegion componentsJoinedByString:@"-"];
    return lang;
}

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIColor*)colorFromColorString:(NSString*)colorString {
    // No value, nothing to do
    if (!colorString) {
        return nil;
    }
    // Validate format
    NSError* error = NULL;
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^(#[0-9A-F]{3}|(0x|#)([0-9A-F]{2})?[0-9A-F]{6})$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSUInteger countMatches = [regex numberOfMatchesInString:colorString options:0 range:NSMakeRange(0, [colorString length])];
    if (!countMatches) {
        return nil;
    }
    // #FAB to #FFAABB
    if ([colorString hasPrefix:@"#"] && [colorString length] == 4) {
        NSString* r = [colorString substringWithRange:NSMakeRange(1, 1)];
        NSString* g = [colorString substringWithRange:NSMakeRange(2, 1)];
        NSString* b = [colorString substringWithRange:NSMakeRange(3, 1)];
        colorString = [NSString stringWithFormat:@"#%@%@%@%@%@%@", r, r, g, g, b, b];
    }
    // #RRGGBB to 0xRRGGBB
    colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];
    // 0xRRGGBB to 0xAARRGGBB
    if ([colorString hasPrefix:@"0x"] && [colorString length] == 8) {
        colorString = [@"0xFF" stringByAppendingString:[colorString substringFromIndex:2]];
    }
    // 0xAARRGGBB to int
    unsigned colorValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:colorString];
    if (![scanner scanHexInt:&colorValue]) {
        return nil;
    }
    // int to UIColor
    return [UIColor colorWithRed:((float)((colorValue & 0x00FF0000) >> 16))/255.0
                           green:((float)((colorValue & 0x0000FF00) >>  8))/255.0
                            blue:((float)((colorValue & 0x000000FF) >>  0))/255.0
                           alpha:((float)((colorValue & 0xFF000000) >> 24))/255.0];
}

+ (NSString *)stringFromTimeInterval:(CFTimeInterval)timeInterval {
    /* NSInteger ms = timeInterval * 1000;
    return [NSString stringWithFormat:@"%0.2ld",(long)ms]; */
    return [NSString stringWithFormat:@"%0.2f",timeInterval];
}

NSInteger getDaysInYear(NSDate* date) {
    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDate *today = date;
    NSInteger dc = [currentCalendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:today];
    return dc;
}

@end
