//
//  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];
}
+ (NSDate *)convertToDateFromStr:(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 *)stringFromDateWithFormat:(NSDate*)aDate format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    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;
}

+ (NSMutableAttributedString *)setTextViewBoldFontOfString:(NSString *)string paragraphStyle:(NSInteger)lineHeight fontSize:(float)size color:(UIColor *)color {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineHeight;
    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize: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;
}
+ (BOOL)checkIsPermission:(NSString *)permission{
    for (NSString *per in [ICRUserUtil sharedInstance].permissions) {
        if ([per isEqualToString:permission]) {
            return YES;
        }
    }
    return NO;
}


+(UILabel *)labelWithTitle:(NSString *)title frame:(CGRect)frame textFont:(UIFont *)titleFont
{
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:frame];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = titleFont;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.numberOfLines = 1;
    
    //设置文字过长时的显示格式,截去尾部...
    titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    titleLabel.text=title;
    
    return titleLabel;
}

+ (UIButton *)buttonWithTitle:(NSString *)title Image:(UIImage *)image frame:(CGRect)frame fontSize:(float)fontSize fontColor:(UIColor *)color
{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setTitle:title forState:UIControlStateNormal];
    button.frame = frame;
    button.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    if (image) {
        [button setImage:image forState:UIControlStateNormal];
    }
    [button setTitleColor:color forState:UIControlStateNormal];
    
    return button;
}

+ (UIButton *)buttonWithImage:(UIImage *)image frame:(CGRect)frame
{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    button.frame = frame;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [button setImage:image forState:UIControlStateNormal];
    
    return button;
}
+ (NSString *)getWeekFromDate{
    NSString *yearWeek = @"";
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit fromDate:[NSDate date]];
    NSString *yearStr = [IBTCommon stringFromDateWithFormat:[NSDate date]  format:@"yyyy-MM-dd"];
    NSString *year = [yearStr substringToIndex:4];
    NSString *month = [yearStr substringWithRange:NSMakeRange(5,2)];
    if (dateComponents.weekOfYear == 1 && [month isEqualToString:@"12"]) {
        yearWeek = [NSString stringWithFormat:@"%ld-%ld", [year integerValue]+1
                    ,(long)dateComponents.weekOfYear];
    }else{
        yearWeek = [NSString stringWithFormat:@"%ld-%ld", (long)[year integerValue]
                    ,(long)dateComponents.weekOfYear];
    }
    
    return yearWeek;
}
+ (NSInteger)getWeeks:(NSInteger)year{
    NSInteger weeks = 0;
    NSString *dateStr = [NSString stringWithFormat:@"%ld-12-31 00:00:00",(long)year];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit ;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateStr];
    
    
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    weeks = [comps weekOfYear];
    if (weeks==1) {
        return 52;
    }else{
        return 53;
    }
}
+ (NSString*)weekdayStringFromDate:(NSDate *)inputDate{
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
}
+(NSString *)countNumAndChangeformat:(NSString *)num{
    int count = 0;
    long long int a = num.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:num];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    return newstring;
}
+ (NSString *)stringDisposeWithFloat:(float)floatValue
{
    NSString *str = [NSString stringWithFormat:@"%.2f",floatValue];
    NSInteger len = str.length;
    for (int i = 0; i < len; i++)
    {
        if (![str  hasSuffix:@"0"])
            break;
        else
            str = [str substringToIndex:[str length]-1];
    }
    if ([str hasSuffix:@"."])//避免像2.0000这样的被解析成2.
    {
        return [str substringToIndex:[str length]-1];//s.substring(0, len - i - 1);
    }
    else
    {
        return str;
    }
}

@end
