//
//  Utilities.m
//  PushSDK
//
//  Created by LiDong on 12-9-6.
//  Copyright (c) 2013年 HXHG. All rights reserved.
//

#import "Utilities.h"
#import "NSString+Digest.h"
#import "IFBarButton.h"
#import <sys/time.h>
#import <netdb.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <sys/types.h>
#import <sys/socket.h>
#import <net/if.h>
#import <net/if_dl.h>
#import <arpa/inet.h>
#import <ifaddrs.h>


#pragma mark -


NSString * const NSStringEmpty = @"";
NSString * const NSStringBlank = @"\x20";

CGRect CGRectPortraitScreen;
CGRect CGRectPortraitLongVC;
CGRect CGRectPortraitShortVC;
CGRect CGRectLandscapeScreen;
CGRect CGRectLandscapeLongVC;
CGRect CGRectLandscapeShortVC;

UIColor *UIColorClear;
UIColor *UIColorWhite;
UIColor *UIColorBlack;
UIColor *UIColorGray;
UIColor *UIColorDarkGray;
UIColor *UIColorLightGray;
UIColor *UIColorDarkCyan;
UIColor *UIColorPDFBackground;
UIColor *UIColorTexturedBackground;
UIColor *UIColorViewFlipsideBackground;
UIColor *UIColorSelectedBackground;

CGColorRef CGColorClear;
CGColorRef CGColorWhite;
CGColorRef CGColorBlack;
CGColorRef CGColorGray;
CGColorRef CGColorDarkGray;
CGColorRef CGColorLightGray;
CGColorRef CGColorDarkCyan;
CGColorRef CGColorPDFBackground;
CGColorRef CGColorTexturedBackground;
CGColorRef CGColorViewFlipsideBackground;
CGColorRef CGColorSelectedBackground;

UIFont *UIFontNormal10;
UIFont *UIFontNormal12;
UIFont *UIFontNormal14;
UIFont *UIFontNormal16;
UIFont *UIFontBold10;
UIFont *UIFontBold12;
UIFont *UIFontBold14;
UIFont *UIFontBold16;
UIFont *UIFontBold18;

NSString * FSDocumentsDirectory;
NSString * FSDownloadsDirectory;
NSString * FSLibraryDirectory;
NSString * FSTmpDownloadsDirectory;
NSString * FSTmpArchiveDirectory;
NSString * FSTmpUnarchiveDirectory;
NSString * FSTmpEmailDirectory;

NSFileManager *theFileManager;
NSDateFormatter *NSMainDateFormatter;


const CGFloat CGRadianPerDegree = M_PI / 180.f;

UIApplication *theApplication;


#pragma mark -


void UIAlert(NSString *title, NSString *message) {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:LS(@"Close") otherButtonTitles:nil];
	
	[alert show];
}

UIBarButtonItem *UIBarButtonItemCreateFlat(NSString *imageName, id target, SEL action) {
    const CGFloat barHeight = UIInterfaceOrientationIsPortrait([theApplication statusBarOrientation]) ? 44 : 32;
    const CGRect buttonFrame = { 0, 0, 32, barHeight };
    UIButton *button = [[IFBarButton alloc] initWithFrame:buttonFrame];
    
    [button setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    [button setImage:UIBarStyledImageNamed(imageName) forState:UIControlStateNormal];
    [button setShowsTouchWhenHighlighted:YES];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    return barButtonItem;
}

NSArray *NSLocalHostNames(void) {
    NSMutableArray *names = [[NSMutableArray alloc] init];
    
	struct ifaddrs *addrs = NULL;
	int error = getifaddrs(&addrs);
	
    if (0 == error) {
        for (const struct ifaddrs *cursor = addrs; cursor; cursor = cursor->ifa_next) {
            const sa_family_t family = cursor->ifa_addr->sa_family;
            
            if ((AF_INET == family || AF_INET6 == family) && 0 == (cursor->ifa_flags & IFF_LOOPBACK)) {
                if(0 == strcmp("en0", cursor->ifa_name) || 0 == strcmp("en1", cursor->ifa_name)) {
                    char cName[INET6_ADDRSTRLEN];
                    
                    if (AF_INET == family) {
                        inet_ntop(family, &((struct sockaddr_in *)cursor->ifa_addr)->sin_addr, cName, INET6_ADDRSTRLEN);
                    } else {
                        inet_ntop(family, &((struct sockaddr_in6 *)cursor->ifa_addr)->sin6_addr, cName, INET6_ADDRSTRLEN);
                    }
                    
                    NSString *name = [[NSString alloc] initWithUTF8String:cName];
                    
                    [names addObject:name];
                }
            }
        }
    }
    
	freeifaddrs(addrs);
    
	return names;
}

NSString *FSPathForNewFileInDirectory(NSString *directory, NSString *fileName, NSString *extension) {
    if (0 == [directory length] || 0 == [fileName length]) {
        return nil;
    }
    char cPath[PATH_MAX + NAME_MAX + 1];
    char cExtension[NAME_MAX + 1];
    const char *cChiefPath = [[directory stringByAppendingPathComponent:fileName] UTF8String];
    const int chiefLength = strnlen(cChiefPath, PATH_MAX);
    char *pPathSuffix = cPath + chiefLength;
    int extLength = 0;
    
    memcpy(cPath, cChiefPath, chiefLength);
    
    if ([extension length] > 0) {
        const char *utf8 = [extension UTF8String];
        
        extLength = strnlen(utf8, NAME_MAX - 1) + 1;
        cExtension[0] = '.';
        memcpy(cExtension + 1, utf8, extLength);
        cExtension[extLength] = '\0';
        memcpy(pPathSuffix, cExtension, extLength + 1);
    } else {
        cPath[chiefLength] = '\0';
        cExtension[0] = '\0';
    }
    
    for (int i = 1; i < 10000; ++ i) {
        if (0 != access(cPath, F_OK)) {
            NSString *resultPath = [[NSString alloc] initWithBytes:cPath length:(chiefLength + extLength) encoding:NSUTF8StringEncoding];
            
            return resultPath;
        }
        extLength = sprintf(pPathSuffix, "-%d%s", i, cExtension);
    }
    
    return nil;
}

NSString *FSStringCreateWithFileSize(const UInt64 size) {
    NSString *result = nil;
    
    if (size >= SIZE_1_GB) {
        result = [[NSString alloc] initWithFormat:@"%.2f GB", size / (double)SIZE_1_GB];
    } else if (size >= SIZE_1_MB) {
        result = [[NSString alloc] initWithFormat:@"%.2f MB", size / (double)SIZE_1_MB];
    } else if (size >= SIZE_1_KB) {
        result = [[NSString alloc] initWithFormat:@"%.2f KB", size / (double)SIZE_1_KB];
    } else {
        result = [[NSString alloc] initWithFormat:@"%u Bytes", (int)size];
    }
    return result;
}

inline CGPoint CGRectGetCenter(CGRect rect) {
    const CGPoint center = { rect.origin.x + rect.size.width / 2.f, rect.origin.y + rect.size.height / 2.f };
    
    return center;
}

UIImage *UIBarStyledImageNamed(NSString *imageName) {
    UIImage *originalImage = [UIImage imageNamed:imageName];
    const CGSize imageSize = [originalImage size];
    
    const CGFloat shadowOffset = 1.f;
    const CGFloat shadowOpacity = .54;
    CGRect imageRect = { { 0 }, imageSize };
    CGRect shadowRect = { { 0, shadowOffset }, imageSize };
    CGRect newRect = CGRectUnion(imageRect, shadowRect);
    const CGImageRef originalCGImage = [originalImage CGImage];
    
    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, originalImage.scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -(newRect.size.height));
    CGContextSaveGState(context);
    CGContextClipToMask(context, shadowRect, originalCGImage);
    CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:0 alpha:shadowOpacity].CGColor);
    CGContextFillRect(context, shadowRect);
    CGContextRestoreGState(context);
    CGContextClipToMask(context, imageRect, originalCGImage);
    CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:1 alpha:1].CGColor);
    CGContextFillRect(context, imageRect);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

