//
//  CommonUtil.m
//  JasonDevelop
//
//  Created by Jason Lee on 2/14/14.
//  Copyright (c) jasondevelop. All rights reserved.
//
@import CoreTelephony.CTCarrier;
@import CoreTelephony.CTCallCenter;
@import CoreTelephony.CTCall;
@import CoreTelephony.CTTelephonyNetworkInfo;


#import "Common.h"
#import "CommonUtil.h"
#import "SortDictionary.h"

#import "UIDeviceUtil.h"

#define ksEmptyString @""

@implementation CommonUtil

#pragma mark - System Util

+ (NSString *)applicationVersion {
    NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    
    //    CGFloat version = [[[UIDevice currentDevice] ] floatValue];
    //    CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
    return  strVersion;
    
}

+ (NSString *)applicationShortVersion {
    NSString *strVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    //    CGFloat version = [[[UIDevice currentDevice] ] floatValue];
    //    CGFloat version = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey] floatValue];
    return  strVersion;
}

+ (NSString *)bundleIdentifier {
    return [[NSBundle mainBundle] bundleIdentifier];
}

+ (CGFloat)deviceSystemVersion {
    static NSUInteger _deviceSystemVersion = -1.0f;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _deviceSystemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    });
    
    return _deviceSystemVersion;
}

+ (NSString *)uniqueIdentifier {
    //uuid 로 변경
    NSString *identifier = ksEmptyString;
    //    NSString *identifier = [[OSUserDefaults defaults] objectForKey:@"MAC_ADD"];
    //
    //    if ([identifier length] == 0 || [identifier isEqual:ksEmptyString]) {
    //        CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    //        NSString *string = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    //
    //        [[OSUserDefaults defaults] setObject:string forKey:@"MAC_ADD"];
    //        [[OSUserDefaults defaults] synchronize];
    //        identifier = string;
    //    }
    
    NSLog(@"===identifier===%@", identifier);
    return identifier;
}

+ (NSString *)deviceName {//////////////////
    return [UIDevice currentDevice].name;
}

+ (CGFloat)hardwareVersion {
    return [UIDeviceUtil hardwareNumber:[UIDeviceUtil hardware]];
}

+ (NSUInteger)hardware {
    return [UIDeviceUtil hardware];
}

+ (void)showCurrentDevice {
    
    UIDevice *device = [UIDevice currentDevice];
    
    NSMutableString *print = [NSMutableString new];
    [print appendFormat:@"\n%@\n", device.name];
    [print appendFormat:@"%@\n", device.systemName];
    [print appendFormat:@"%@\n", device.model];
    [print appendFormat:@"%@\n", device.localizedModel];
    [print appendFormat:@"%zd\n", device.userInterfaceIdiom];
    [print appendFormat:@"%@\n", [UIDeviceUtil hardwareSimpleDescription]];
}

#pragma makr - Locale
+ (NSString *)countryCode {
    return [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
}


#pragma mark - Network Util

+ (BOOL)roamingCheck {
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [networkInfo subscriberCellularProvider];
    
    NSString *carrierName = [carrier carrierName]; //통신사를 받아올 수 있다.
    NSLog(@"Carrier: %@", carrierName);
    
    NSString *mnc = [carrier mobileNetworkCode]; //통신사를 받아올 수 있다.
    NSLog(@"mnc: %@", mnc);
    
    NSString *mcc = [carrier mobileCountryCode]; // 국가코드를 받아올 수 있다.
    NSLog(@"Mobile Country Code (MCC): %@", mcc);
    
    BOOL network = NO;
    
    if ([mnc isEqualToString:@"05"] || [mnc isEqualToString:@"06"] || [mnc isEqualToString:@"08"] ) { //mnc code
        if ([mcc isEqualToString:@"450"]) {  //국가 코드
            network = YES;
        }
    }
    
    return network;
}


+ (BOOL)isOnPhoneCall {
    
    CTCallCenter *callCenter = [[CTCallCenter alloc] init];
    for (CTCall *call in callCenter.currentCalls)  {
        if (call.callState == CTCallStateConnected) {
            return YES;
        }
    }
    return NO;
}



#pragma mark - File Util
+(NSString*)getPath:(NSString *)lastPath {
    NSArray *paths				= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:lastPath];
}


+(BOOL)isExistFile:(NSString*)filePath {
    BOOL isExist = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:filePath])
        isExist = YES;
    else
        isExist = NO;
    
    return isExist;
}

+ (BOOL)createFile:(NSString*)filePath {
    BOOL	bCreate = NO;
    
    NSLog(@"document file path : %@", filePath);
    //파일의 존재 유무 검사 및 없으면 생성
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isFile = [fileManager fileExistsAtPath:filePath];
    
    if (isFile | [fileManager createFileAtPath:filePath contents:nil attributes:nil]){
        bCreate = YES;
    }else{
        bCreate = NO;
    }
    
    return bCreate;
}

+ (BOOL)deleteFile:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filepath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:filepath error:nil];
    
    return YES;
}

#pragma mark - UI Util

+ (id)instantiateViewControllerWithIdentifier:(NSString *)identifier storyboardName:(NSString *)storyboardName
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    return [sb instantiateViewControllerWithIdentifier:identifier];
}

+ (UIViewController *)currentViewController {
    
    id appDelegate = [UIApplication sharedApplication].delegate;
    UIViewController *vc = (UINavigationController *)[[appDelegate window] rootViewController];
    
    if (vc.presentedViewController) {
        while (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }

        if ([vc isKindOfClass:[UINavigationController class]]) {
            NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
            vc = [vcArray objectAtIndex:vcArray.count - 1];
        }
        return vc;
    }
    
    if (vc.presentingViewController && (vc.modalPresentationStyle == UIModalPresentationFullScreen)) {
        vc = vc.presentingViewController;
    }
    
    if ([NSClassFromString(@"ECSlidingViewController") class] && [vc isKindOfClass:[NSClassFromString(@"ECSlidingViewController") class]]) {
        id slideController = vc;
        vc = (UINavigationController *)[slideController topViewController];
    }
    
    if ([vc isKindOfClass:[UINavigationController class]]) {
        NSArray *vcArray = ((UINavigationController *)vc).viewControllers;
        vc = [vcArray objectAtIndex:vcArray.count - 1];
    }
    
    return vc;
}

+ (UIView *)topView
{
    UIView *topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
    
    while ([topView isKindOfClass:NSClassFromString(@"UITransitionView")]) {
        topView = [[topView subviews] lastObject];
    }
    
    if ([topView isKindOfClass:NSClassFromString(@"CustomLoadingView")]) {
        
        topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
        topView = [topView subviews][topView.subviews.count - 2];
    }
    
    topView = topView == nil ? [[UIApplication sharedApplication] keyWindow] : topView;
    return topView;
}


+ (CGRect)mainScreenBounds {
    CGRect screenRect = [UIScreen mainScreen].bounds;
    return screenRect;
}


//해당 컨테이너로부터 해당 객체의 중앙 지점을 연산하여 반환함.
+ (CGRect)getCenterPosition:(id)object fromContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
    CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
    
    if (object && container) {
        
        CGRect cframe = [container frame];
        CGRect oframe = [object frame];
        
        float nHeight = hasNavigationBar ? 44.0 : 0;
        float tHeight = hasTabBar ? 59.0 : 0;
        
        float x = ((cframe.size.width - oframe.size.width) / 2);
        float y = (cframe.size.height - (oframe.size.height - nHeight - tHeight)) / 2;
        
        frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
    }
    
    return frame;
}

+ (CGRect)centerRect:(id)object fromContainer:(id)container {
    CGRect frame = CGRectMake(0.0, 0.0, 0.0, 0.0);
    
    if (object && container) {
        
        CGRect cframe = [container frame];
        CGRect oframe = [object frame];
        
        float x = ((cframe.size.width - oframe.size.width) / 2);
        float y = (cframe.size.height - (oframe.size.height)) / 2;
        
        frame = CGRectMake(x, y, oframe.size.width, oframe.size.height);
    }
    
    return frame;
}

//해당 객체를 해당 컨테이너의 중앙(가로*세로)에 위치시킴.
+ (void)moveToCenter:(id)object withContainer:(id)container hasNavigationBar:(BOOL)hasNavigationBar hasTabBar:(BOOL)hasTabBar {
    
    CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:hasNavigationBar hasTabBar:hasTabBar];
    
    UIView *oView = (UIView *)object;
    [oView setFrame:rect];
}

//해당 객체를 해당 컨테이너의 중앙(가로)에 위치시킴.
+ (void)moveToCenterHorizon:(id)object withContainer:(id)container {
    CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
    
    CGRect oframe = [object frame];
    oframe.origin.x = rect.origin.x;
    
    UIView *oView = (UIView *)object;
    [oView setFrame:oframe];
}

//해당 객체를 해당 컨테이너의 중앙(세로)에 위치시킴.
+ (void)moveToCenterVertical:(id)object withContainer:(id)container {
    CGRect rect = [CommonUtil getCenterPosition:object fromContainer:container hasNavigationBar:NO hasTabBar:NO];
    
    CGRect oframe = [object frame];
    oframe.origin.y = rect.origin.y;
    
    UIView *oView = (UIView *)object;
    [oView setFrame:oframe];
}

+ (CGSize)sizeWithString:(NSString *)text font:(UIFont *)font constrainedToSize:(CGSize)constrainedToSize lineBreakMode:(NSLineBreakMode)lineBreakMode {
    CGSize size = CGSizeZero;
    
    if (IOS_VERSION >= 7.0f) {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){constrainedToSize.width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        size = rect.size;
    }
    
    return size;
}


+ (float)sizeWithStringHeight:(NSString *)text font:(UIFont *)font constrainedToSize:(float)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
    float size = 0;
    
    if (IOS_VERSION >= 7.0f) {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:font}];
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        size = rect.size.height;
    }
    
    return size;
}


+ (CGFloat)getLabelRealWidth:(UILabel *)label fixedWidth:(CGFloat)fixedWidth {
    CGFloat width = 0.0f;
    CGRect oriRect = label.frame;
    CGRect chRect = label.frame;
    chRect.size.width = fixedWidth;
    label.frame = chRect;
    
    
    [label sizeToFit];
    width = label.frame.size.width;
    
    
    label.frame = oriRect;
    
    return width;
}

+ (CGFloat)getLabelRealHeight:(UILabel *)label {
    
    CGFloat height = 0.0f;
    CGRect oriRect = label.frame;
    
    [label sizeToFit];
    height = label.frame.size.height;
    
    label.frame = oriRect;
    
    return height;
}

+ (CGSize)getLabelRealSize:(UILabel *)label fixedWdith:(CGFloat)fixedWidth {
    CGFloat width = [CommonUtil getLabelRealWidth:label fixedWidth:fixedWidth];
    CGFloat height = [CommonUtil getLabelRealHeight:label];
    return CGSizeMake(width, height);
}

+ (CGSize)getSizeFromString:(NSString *)string font:(UIFont *)font width:(CGFloat)fixedWidth {
    if ([string isEqualToString:ksEmptyString]) {
        return CGSizeZero;
    }
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
    CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:context];
    
    r = CGRectIntegral(r);
    return r.size;
}

+ (CGSize)getSizeFromAttributeString:(NSAttributedString *)string width:(CGFloat)fixedWidth {
    if ([string.string isEqualToString:ksEmptyString]) {
        return CGSizeZero;
    }
    
    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize labelSize = (CGSize){fixedWidth, FLT_MAX};
    CGRect r = [string boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin context:context];
    
    r = CGRectIntegral(r);
    return r.size;
}

/**
 NIB에서 해당 뷰를 로드함.
 @return NSArray * 뷰어레이
 */
+ (NSArray *)nibViews:(NSString *)nibName {
    UINib *nib = [UINib nibWithNibName:nibName bundle:[NSBundle mainBundle]];
    return [nib instantiateWithOwner:nil options:nil];
}



#pragma mark - Date Util

+ (NSCalendar *)calendar {
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    return cal;
}

+ (NSDateFormatter *)dateFormatter {
    static NSDateFormatter *__shareDateFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __shareDateFormatter = [[NSDateFormatter alloc] init];
        NSLocale *locale = [NSLocale currentLocale];
        [__shareDateFormatter setLocale:locale];
    });
    
    return __shareDateFormatter;
}

+ (NSString *)currentMonth {
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY.MM";
    
    NSString *title = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
    return title;
}

+ (NSDateComponents *)dateComponents:(NSDate *)date {
    
    NSCalendar *calendar = [CommonUtil calendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
                                                         NSCalendarUnitMonth |
                                                         NSCalendarUnitDay   |
                                                         NSCalendarUnitHour  |
                                                         NSCalendarUnitMinute|
                                                         NSCalendarUnitSecond|
                                                         NSCalendarUnitTimeZone) fromDate:date];
    return components;
}

+ (NSDateComponents *)dateComponents:(NSDate *)date timezone:(NSTimeZone *)timezone {
    
    NSCalendar *calendar = [CommonUtil calendar];
    [calendar setTimeZone:timezone];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear |
                                                         NSCalendarUnitMonth |
                                                         NSCalendarUnitDay   |
                                                         NSCalendarUnitHour  |
                                                         NSCalendarUnitMinute|
                                                         NSCalendarUnitSecond|
                                                         NSCalendarUnitTimeZone) fromDate:date];
    return components;
}


//Date객체를 String객체로 전환

+ (NSString *)stringFromDate:(NSDate *)date {
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY/MM/dd";
    
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

+ (NSString *)stringFromDateTime:(NSDate *)date {
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"yyyyMMddHHmmss";
    
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

+ (NSString *)birthStringFromDate:(NSDate *)date {
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYYMMdd";
    
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}


+ (NSString *)stringFromDate2:(NSDate *)date {
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY-MM-dd";
    
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}


+ (NSString *)stringFromString:(NSString *)dateString {
    NSDateComponents *components = [CommonUtil dateComponentsFromString:dateString];
    return [CommonUtil stringFromDateComponents:components];
}


+ (NSDateComponents *)dateComponentsFromString:(NSString *)dateString {

    NSDateComponents *dateComp = nil;
    
    if (dateString && dateString.length == 6) {//19990101 타입
        dateComp = [[NSDateComponents alloc] init];
        dateComp.year = [[dateString substringToIndex:4] intValue];
        dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
        
    } else if (dateString && dateString.length == 8) {//19990101 타입
        dateComp = [[NSDateComponents alloc] init];
        dateComp.year = [[dateString substringToIndex:4] intValue];
        dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
        dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
        
    } else if (dateString && dateString.length == 14) {//19990101010101 타입
        dateComp = [[NSDateComponents alloc] init];
        dateComp.year = [[dateString substringToIndex:4] intValue];
        dateComp.month = [[dateString substringWithRange:NSMakeRange(4, 2)] intValue];
        dateComp.day = [[dateString substringWithRange:NSMakeRange(6, 2)] intValue];
        dateComp.hour = [[dateString substringWithRange:NSMakeRange(8, 2)] intValue];
        dateComp.minute = [[dateString substringWithRange:NSMakeRange(10, 2)] intValue];
        dateComp.second = [[dateString substringWithRange:NSMakeRange(12, 2)] intValue];
        
    } else if ([dateString rangeOfString:@"-"].location != NSNotFound) {
        NSArray *dateArray = [dateString componentsSeparatedByString:@"-"];
        if (dateArray && dateArray.count > 0) {
            dateComp = [[NSDateComponents alloc] init];
            dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
            dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
            dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
        }
    } else if ([dateString rangeOfString:@"/"].location != NSNotFound) {
        NSArray *dateArray = [dateString componentsSeparatedByString:@"/"];
        if (dateArray && dateArray.count > 0) {
            dateComp = [[NSDateComponents alloc] init];
            dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
            dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
            dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
        }
    } else if ([dateString rangeOfString:@"."].location != NSNotFound) {
        NSArray *dateArray = [dateString componentsSeparatedByString:@"."];
        if (dateArray && dateArray.count > 0) {
            dateComp = [[NSDateComponents alloc] init];
            dateComp.year = dateArray.count >= 1 ? [dateArray[0] intValue] : 0;
            dateComp.month = dateArray.count >= 2 ? [dateArray[1] intValue] : 0;
            dateComp.day = dateArray.count >= 3 ? [dateArray[2] intValue] : 0;
        }
    }
    
    return dateComp;
}


+ (NSDateComponents *)dateComponentsFromUTCString:(NSString *)utcString {
    
    NSDateFormatter* df_local = [[CommonUtil dateFormatter] copy];
    [df_local setTimeZone:[NSTimeZone systemTimeZone]];
    [df_local setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSDate *locTime = [df_local dateFromString:utcString];
    
    return [CommonUtil dateComponents:locTime];
}

+ (NSDate *)dateFromDateString:(NSString *)dateString {
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
    NSDate *newDate = [[CommonUtil calendar] dateFromComponents:ds];
    return newDate;
}

+ (NSString *)stringFromDateComponents:(NSDateComponents *)components {
    NSMutableString *rString = [NSMutableString new];
    
    if (components.year > 0) {
        [rString appendString:[NSString stringWithFormat:@"%zd년", (NSInteger)components.year]];
    }
    if (components.month > 0) {
        if (rString.length > 0) {
            [rString appendString:@" "];
        }
        [rString appendString:[NSString stringWithFormat:@"%zd월", (NSInteger)components.month]];
    }
    if (components.day > 0) {
        if (rString.length > 0) {
            [rString appendString:@" "];
        }
        [rString appendString:[NSString stringWithFormat:@"%zd일", (NSInteger)components.day]];
    }
    return rString;
}


+ (NSString *)stringFromDateComponents2:(NSDateComponents *)components {
    
    NSString *month = components.month < 10 ? [NSString stringWithFormat:@"0%zd", components.month] : [NSString stringWithFormat:@"%zd", components.month];
    NSString *day = components.day < 10 ? [NSString stringWithFormat:@"0%zd", components.day] : [NSString stringWithFormat:@"%zd", components.day];
    
    NSString *rString = [NSString stringWithFormat:@"%zd%@%@", components.year, month, day];
    return rString;
}



+ (NSString *)stringYearMonthFromDateComponents:(NSDateComponents *)components {
    NSMutableString *rString = [NSMutableString new];
    
    if (components.year > 0) {
        [rString appendString:[NSString stringWithFormat:@"%zd.", (NSInteger)components.year]];
    }
    if (components.month > 0) {
        if (components.month < 10) {
            [rString appendString:[NSString stringWithFormat:@"0%zd", (NSInteger)components.month]];
        } else {
            [rString appendString:[NSString stringWithFormat:@"%zd", (NSInteger)components.month]];
        }
    }
    
    return rString;
}


+ (NSString *)paramMonthFromDateString:(NSString *)dateString {
    
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
    ds.day = 1;
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYYMM";
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

+ (NSDate *)dateFrom:(NSDate *)date adjustDay:(NSInteger)day {
    
    NSDateComponents *ds = [CommonUtil dateComponents:date];
    ds.day += day;
    
    NSDate *adjustDate = [[CommonUtil calendar] dateFromComponents:ds];
    return adjustDate;
}


//현재 로컬시간을 UTC로 변환합니다.
+ (NSString *)UTCDateStringFromLocal:(NSString *)locDateString {
    NSDateFormatter *df = [CommonUtil dateFormatter];
    [df setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *locDate = [df dateFromString:locDateString];
    
    NSDateFormatter *dfu = [[CommonUtil dateFormatter] copy];
    dfu.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
    
    NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    [dfu setTimeZone:utc];
    NSString *timeStamp = [dfu stringFromDate:locDate];
    timeStamp = [NSString stringWithFormat:@"%@Z",timeStamp];
    return timeStamp;
}

//UTC 시간을 현재 로컬 시간을 변환합니다.
+ (NSString *)localDateFromUTC:(NSString *)utcDateString {
    NSDateFormatter *df = [CommonUtil dateFormatter];
    [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    NSDate *utcDate = [df dateFromString:utcDateString];
    
    NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
    [dfl setTimeZone:[NSTimeZone systemTimeZone]];
    [dfl setDateFormat:@"yyyyMMddHHmmss"];
    
    NSString* localString = [dfl stringFromDate:utcDate];
    return localString;
}

+ (NSString *)localDateFromUTC2:(NSString *)utcDateString {
    NSDateFormatter *df = [[CommonUtil dateFormatter] copy];
    NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    [df setTimeZone:utc];
    [df setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *utcDate = [df dateFromString:utcDateString];
    
    NSDateFormatter* dfl = [[CommonUtil dateFormatter] copy];
    [dfl setTimeZone:[NSTimeZone systemTimeZone]];
    [dfl setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString* localString = [dfl stringFromDate:utcDate];
    return localString;
}


+ (NSString *)formattedDate:(NSString *)dateString {
    
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY년 M월 d일";
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

+ (NSString *)formattedDate2:(NSString *)dateString {
    
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY.MM.dd";
    
    NSDate *date = [[CommonUtil calendar]dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

//기본 날짜포맷을 반환
+ (NSString *)formattedDate3:(NSString *)datetime {
    
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:datetime];
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY년 MM월 dd일";
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

+ (NSString *)formattedMonthDate:(NSString *)dateString {
    
    NSDateComponents *ds = [CommonUtil dateComponentsFromString:dateString];
    
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"YYYY.MM";
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}

#pragma mark - TimeUtil

+ (NSString *)formattedTime:(NSString *)timeString {
    
    NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"HH시 mm분";
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}


+ (NSString *)formattedTime2:(NSString *)timeString {
    
    NSDateComponents *ds = [CommonUtil timeComponentsFromString:timeString];
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"HH시 mm분";
    
    NSString *period = ds.hour < 12 ? @"오전" : @"오후";
    if ([period isEqualToString:@"오후"]) {
        ds.hour -= 12;
    }
    
    NSDate *date = [[CommonUtil calendar] dateFromComponents:ds];
    return [NSString stringWithFormat:@"%@ %@", period, [df stringFromDate:date]];
}



+ (NSDateComponents *)timeComponentsFromString:(NSString *)timeString {
    NSDateComponents *dateComp = [CommonUtil dateComponents:[NSDate date]];
    
    if (timeString && [timeString rangeOfString:@"시 "].location != NSNotFound) {//00시 00분 타입
        NSArray *timeArray = [timeString componentsSeparatedByString:@" "]; //시와 분을 나눔
        
        NSString *hour = [timeArray firstObject];
        hour = [hour stringByReplacingOccurrencesOfString:@"시" withString:@""];
        
        NSString *minute = [timeArray lastObject];
        minute = [minute stringByReplacingOccurrencesOfString:@"분" withString:@""];
        
        dateComp.hour = [hour intValue];
        dateComp.minute = [minute intValue];
        
    } else if ([timeString rangeOfString:@":"].location != NSNotFound) {
        NSArray *timeArray = [timeString componentsSeparatedByString:@":"];
        
        if (timeArray && timeArray.count > 0) {
            dateComp.hour = timeArray.count >= 1 ? [timeArray[0] intValue] : 0;
            dateComp.minute = timeArray.count >= 2 ? [timeArray[1] intValue] : 0;
        }
    }
    
    return dateComp;
}

+ (NSString *)stringFromTime:(NSDate *)date {
    NSDateFormatter *df = [CommonUtil dateFormatter];
    df.dateFormat = @"HH:mm";
    
    return [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
}



#pragma mark - StringUtil
+ (NSNumberFormatter *)numberFormatter {
    static NSNumberFormatter *__shareNumberFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __shareNumberFormatter = [[NSNumberFormatter alloc] init];
        NSLocale *locale = [NSLocale currentLocale];
        [__shareNumberFormatter setLocale:locale];
    });
    
    return __shareNumberFormatter;
}

+ (NSString *)numberString:(NSInteger)number {
    NSNumberFormatter *formatter = [CommonUtil numberFormatter];
    
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.usesGroupingSeparator = YES;
    [formatter setGroupingSeparator:@","];
    
    NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
    return formattedString;
}

+ (NSString *)currencyString:(NSInteger)number {
    NSString *currency = [NSString stringWithFormat:@"%@ 원", @"0"];
    if (number <= 0) {
        
        return currency;
    }
    
    NSNumberFormatter *formatter = [CommonUtil numberFormatter];
    
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.usesGroupingSeparator = YES;
    [formatter setGroupingSeparator:@","];
    
    NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
    currency = [NSString stringWithFormat:@"%@ 원", formattedString];
    
    return currency;
}

+ (NSString *)currencyString2:(NSInteger)number {
    NSString *currency = [NSString stringWithFormat:@"%@원", @"0"];
    if (number <= 0) {
        return currency;
    }
    
    NSNumberFormatter *formatter = [CommonUtil numberFormatter];
    
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.usesGroupingSeparator = YES;
    [formatter setGroupingSeparator:@","];
    
    NSString *formattedString = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:[NSNumber numberWithInteger:number]]];
    currency = [NSString stringWithFormat:@"%@원", formattedString];
    
    return currency;
}


+ (NSString *)svcNoString:(NSString *)svcNo {
    //0103333333
    
    NSMutableString *tmpSvcNo = [NSMutableString stringWithString:svcNo];
    if (svcNo.length == 10) {
        [tmpSvcNo insertString:@"-" atIndex:3];
        [tmpSvcNo insertString:@"-" atIndex:7];
    } else if (svcNo.length == 11) {
        [tmpSvcNo insertString:@"-" atIndex:3];
        [tmpSvcNo insertString:@"-" atIndex:8];
    }
    return tmpSvcNo;
}


+ (NSString *)cutSaName:(NSString *)saName {
    NSRange range = [saName rangeOfString:@"]"];
    NSString *rSaName = nil;
    
    if (range.location != NSNotFound) {
        rSaName = [saName substringWithRange:NSMakeRange(1, range.location-1)];
    }
    return rSaName;
}

+ (NSInteger)getIntegerFromCurrency:(NSString *)currency {
    NSInteger rvalue = 0;
    NSString *tmp = [NSString stringWithString:currency];
    NSRange fRange = [currency rangeOfString:NSLocalizedString(@"Won", @"원")];
    if (fRange.location == currency.length-1) {
        tmp = [currency stringByReplacingOccurrencesOfString:NSLocalizedString(@"Won", @"원") withString:ksEmptyString];
    }
    
    tmp = [tmp stringByReplacingOccurrencesOfString:@"," withString:ksEmptyString];
    rvalue = [tmp intValue];
    return rvalue;
}


+ (NSString *)formattedPhoneNumber:(NSString *)phoneNumber {
    if ([phoneNumber rangeOfString:@"-"].location != NSNotFound) {//이미 포맷에 맞춰진 경우는 리턴
        return phoneNumber;
    }
    
    NSMutableString *rString = [NSMutableString stringWithString:phoneNumber];
    
    NSInteger lastIndex = phoneNumber.length - 3;
    [rString insertString:@"-" atIndex:3];
    [rString insertString:@"-" atIndex:lastIndex];
    
    return rString;
}

+ (NSString *)formattedIAId:(NSString *)iaId {
    NSMutableString *formatIAId = [NSMutableString stringWithString:iaId];
    [formatIAId replaceCharactersInRange:NSMakeRange(formatIAId.length-3, 3) withString:@"***"];
    return formatIAId;
}



+ (NSInteger)countForOccurrencesOfString:(NSString *)occurString {
    
    NSInteger count = 0, length = [occurString length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound) {
        range = [occurString rangeOfString:occurString options:0 range:range];
        if(range.location != NSNotFound) {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++;
        }
    }
    
    return count;
}


+(NSString *)URLEncoding:(NSString *)sender{
    NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                                     NULL,
                                                                                                     (CFStringRef)sender,
                                                                                                     NULL,
                                                                                                     (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                                     kCFStringEncodingUTF8 ));
    return encodedString;
}


+(NSString *)URLDecoding:(NSString *)sender {
    // Decode a percent escape encoded string.
    NSString *decodeString = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                   (CFStringRef) sender,
                                                                                                                   CFSTR(""),
                                                                                                                   kCFStringEncodingUTF8));
    return decodeString;
}



#pragma getUrlPostUrl
+ (NSString *)switchPostUrl:(NSString *)getUrl{
    NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
    NSString *splturl = [urlLst objectAtIndex:1];
    return splturl;
}

+ (NSString *)getUrl:(NSString *)getUrl{
    NSString *url;
    NSArray *urlLst = [getUrl componentsSeparatedByString:@"?"];
    
    url = [urlLst objectAtIndex:0];
    
    return url;
}


+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    return returnValue;
}

#pragma mark - TimeZone Dictionary

+ (SortDictionary *)timeZoneDict {
    NSString *plist = [[NSBundle mainBundle] pathForResource:@"TimeZoneCode" ofType:@"plist"];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:plist];
    
    return [[SortDictionary alloc] initWithDictionary:dic];
}

@end
