//
//  IBTCommon.m
//  AceMTer
//
//  Created by Xummer on 2/27/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "IBTCommon.h"
#import "ICRUserUtil.h"

@implementation IBTFileData

@end

@implementation IBTCommon

+ (NSString *)localizableString:(NSString *)text
{
    /*
     NSString *settingLanguge = [[TWDocument unarchive] language];
     
     NSString *directoryName = [NSString stringWithString:settingLanguge];
     directoryName = [directoryName stringByAppendingString:@".lproj"];
     NSString *tableName = [directoryName stringByAppendingPathComponent:@"Localizable"];
     text = NSLocalizedStringFromTable(text, tableName, text);
     */
    
    return NSLocalizedString(text, nil);
}

+ (UIImage *)localizableImage:(NSString *)name
{
    UIImage *image = nil;
    /*
     NSString *settingLanguge = [[TWDocument unarchive] language];
     
     NSString *directoryName = [NSString stringWithString:settingLanguge];
     directoryName = [directoryName stringByAppendingString:@".lproj"];
     NSString *filePath = [[NSBundle mainBundle] pathForResource:name ofType:nil inDirectory:directoryName];
     image = [UIImage imageWithContentsOfFile:filePath];
     */
    return image;
}

+ (UIImage *)appIcon {
    /*
     CFBundleIcons =     {
     CFBundlePrimaryIcon =         {
     CFBundleIconFiles =             (
     AppIcon29x29,
     AppIcon40x40,
     AppIcon57x57,
     AppIcon60x60,
     AppIcon120x120
     );
     };
     };
     */
    
    NSArray *arrIcons = [[NSBundle mainBundle] infoDictionary][ @"CFBundleIcons" ][ @"CFBundlePrimaryIcon" ][ @"CFBundleIconFiles" ];
    UIImage *appIcon = nil;
    NSUInteger uiIconCount = [arrIcons count];
    for (NSInteger i = uiIconCount - 1; i >= 0; i -- ) {
        appIcon = [UIImage imageNamed:arrIcons[ i ]];
        if (appIcon) {
            break;
        }
    }
    
    return appIcon;
}

+ (BOOL)isLegalString:(NSString *)string WithRegex:(NSString *)regexStr
{
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
    if (string != nil && regex != nil) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
        if (firstMatch) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - Thread
+ (void)runOnMainThreadWithoutDeadlocking:(void (^)(void))block {
    if ([NSThread isMainThread]) {
        block();
    }
    else{
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

+ (NSString *)archivePathForCurrentUser {
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    NSString *userName = [userUtil userName];
    if (!userName.length) return nil;
    
    NSString *orgCode = [userUtil orgCode];
    if (!orgCode.length) {
        return nil;
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
    
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    if (appName == nil) {
        appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
        
        if (appName == nil) appName = @"XFFruit";
    }
    
    NSString *result = [basePath stringByAppendingPathComponent:appName];
    if (result != nil) {
        result = [result stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@", orgCode, userName]];
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:result]) {
        [fileManager createDirectoryAtPath:result
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    
    return result;
}

+ (NSString *)archivePathForTmpImages {
    NSString *archivePath = [[self class] archivePathForCurrentUser];
    if (!archivePath.length) {
        return nil;
    }
    
    NSString *dirName = @"images";
    NSString *result = [archivePath stringByAppendingPathComponent:dirName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:result]) {
        [fileManager createDirectoryAtPath:result
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    
    return result;
}

+ (IBTFileData *)saveImageToLocal:(UIImage *)imageToSave {
    NSString *imgName = [NSString stringWithFormat:@"ICRIMG-%@.JPG", [[NSDate date] YMDHMSFormatterString]];
    NSString *imgPath = [[IBTCommon archivePathForTmpImages] stringByAppendingPathComponent:imgName];
    NSData *imgData = UIImageJPEGRepresentation(imageToSave, .6f);
    
    if ([imgData writeToFile:imgPath atomically:YES])
    {
        IBTFileData *fileData = [[IBTFileData alloc] init];
        fileData.fileName = imgName;
        fileData.filePath = imgPath;
        fileData.fileData = imgData;
        return fileData;
    }
    else {
        return nil;
    }
}

+ (NSDate *)convertToDateFrom:(NSString *)dateString{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy.MM.dd"];
    return [formatter dateFromString:dateString];
}
+ (NSString *)stringFromDate:(NSDate*)aDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [formatter stringFromDate:aDate];
    return dateString;
}

+ (NSString*)dictionaryToJson:(id)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
+ (NSString *)checkString:(NSString *)str
{
    
    return (str)?str:@"";
}
+ (NSString *)checkNull:(id)data {

    return data == [NSNull null] ? @"" : data;
  
}
+ (BOOL)checkStringIsNilOrSpance:(NSString *)str {
    if (!str || [str isEqualToString:@"" ] || [str isEqual:[NSNull null]]) {
        return YES;
    } else {
        return NO;
    }
}
+ (NSMutableAttributedString *)setTextViewFontOfString:(NSString *)string paragraphStyle:(NSInteger)lineHeight fontSize:(float)size color:(UIColor *)color {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineHeight;
    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:size],NSForegroundColorAttributeName :color, NSParagraphStyleAttributeName:paragraphStyle};
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes];
    return attributeStr;
}

+ (NSString *)trimmingCharacters:(NSString *)str{
    NSString *newStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return newStr;
}
+ (int)compareDate:(NSString*)oneDate withDate:(NSString*)twoDate{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:oneDate];
    dt2 = [df dateFromString:twoDate];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

@end
