//
//  NSString+GM.m
//  Gengmei
//
//  Created by licong on 12/28/15.
//  Copyright © 2015 Wanmeichuangyi. All rights reserved.
//

#import "NSString+GM.h"
#import "NSNull+Empty.h"



@implementation NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (![string length]) return nil;
    
    NSData *decoded = nil;
    
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    
    if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])
    {
        decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];
    }
    else
    
#endif
        
    {
        decoded = [[self alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    }
    
    return [decoded length]? decoded: nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    if (![self length]) return nil;
    
    NSString *encoded = nil;
    
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    
    if (![NSData instancesRespondToSelector:@selector(base64EncodedStringWithOptions:)])
    {
        encoded = [self base64Encoding];
    }
    else
    
#endif
    
    {
        switch (wrapWidth)
        {
            case 64:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            }
            case 76:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
            }
            default:
            {
                encoded = [self base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
            }
        }
    }
    
    if (!wrapWidth || wrapWidth >= [encoded length])
    {
        return encoded;
    }
    
    wrapWidth = (wrapWidth / 4) * 4;
    NSMutableString *result = [NSMutableString string];
    for (NSUInteger i = 0; i < [encoded length]; i+= wrapWidth)
    {
        if (i + wrapWidth >= [encoded length])
        {
            [result appendString:[encoded substringFromIndex:i]];
            break;
        }
        [result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];
        [result appendString:@"\r\n"];
    }
    
    return result;
}

- (NSString *)base64EncodedString
{
    return [self base64EncodedStringWithWrapWidth:0];
}

@end


@implementation NSString (GM)


+ (NSString *)safeStringWithString:(NSString *)string{
    
    if ([string isNonEmpty]) {
        return string;
    }else{
        return @"";
    }
}

- (BOOL)isNonEmpty {
    
    NSMutableCharacterSet *emptyStringSet = [[NSMutableCharacterSet alloc] init];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"　"]];
    if ([self length] == 0) {
        return NO;
    }
    NSString* str = [self stringByTrimmingCharactersInSet:emptyStringSet];
    return [str length] > 0;
}

+ (NSString *)convertToPrettyPrintedJsonString:(id)object
{
    return [self convertToJsonString:object withOption:NSJSONWritingPrettyPrinted];
}

+ (NSString *)convertToBriefJsonString:(id)object
{
    return [self convertToJsonString:object withOption:0];;
}

+ (NSString *)convertToJsonString:(id)object withOption:(NSJSONWritingOptions)opt {
    NSString *jsonString = @"";
    NSError *error;
    if (!object) {
        NSAssert(0, @"convertToJsonString object 是nil");
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:opt
                                                         error:&error];
    if (!jsonData) {
        NSAssert(0, @"convertToJsonString NSJSONSerialization 出现错误");
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    if (jsonString == nil) {
        NSAssert(0, @"convertToJsonString jsonString 是nil");
        jsonString = @"";
    }
    return jsonString;
}

+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum{
    
    NSString *ALL = @"\\d{11}$";
    NSPredicate *regextestall = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ALL];
    return [regextestall evaluateWithObject:mobileNum];
}
- (unsigned long long)unsignedLongLongValue {
    
    return self.longLongValue;
}
//利用正则表达式验证
+ (BOOL)isValidateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

@end



@implementation NSString (paresQuery)

- (NSDictionary*)urlQueryToDictionary{
    NSURL* url1 = [NSURL URLWithString:self];
    if (!url1) {
        return nil;
    }
    NSString* query = [url1 query];
    return [query queryToDictionary];
}

- (NSDictionary*)queryToDictionary {
    @try {
        NSMutableDictionary* dict = [NSMutableDictionary dictionary];
        NSArray* components = [self componentsSeparatedByString:@"&"];
        for (NSString* component in components) {
            NSArray* keyValue = [component componentsSeparatedByString:@"="];
            if ([keyValue count] > 1) {
                NSString * key = [[keyValue objectAtIndex:0] URLDecodedString];
                NSString * value = [keyValue objectAtIndex:1];
                
                //参数中依然包含超过2个“=”号（多数发生在common_webview后的url参数中），则后面的数组的元素需要拼接成一个字符串
                if ([keyValue count]>2) {
                    for (int i=2; i<[keyValue count]; i++) {
                        value=[value stringByAppendingString:@"="];
                        value=[value stringByAppendingString:keyValue[i]];
                    }
                }
                
                //因为这种情况服务器和客户端都转义了一次，所以要两次反转义还原中文
                while ([value rangeOfString:@"%"].length != 0) {
                    value = [value URLDecodedString];
                }
                [dict setObject: value forKey: key];
            }
        }
        return dict;
    }
    @catch (NSException *exception) {}
}

@end




@implementation NSString (calculatorSize)


- (CGSize)sizeWithFont:(UIFont *)font boundSize:(CGSize)size{
    return [self sizeWithFont:font boundSize:size lineSpacing:0];
}

- (CGSize)sizeWithFont:(UIFont *)font boundSize:(CGSize)size lineSpacing:(CGFloat)lineSpacing{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineSpacing = lineSpacing;
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize resultSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    return CGSizeMake(ceil(resultSize.width), ceil(resultSize.height));
}


@end



@implementation NSString (URLEncoding)

- (NSString *)URLEncodedString {
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                             (CFStringRef)self,
                                                                                             NULL,
                                                                                             CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                                             kCFStringEncodingUTF8));
    return result;
}

- (NSString*)URLDecodedString {
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                                                             (CFStringRef)self,
                                                                                                             CFSTR(""),
                                                                                                             kCFStringEncodingUTF8));
    return result;
}

- (NSString *)URLEncodeString {
    NSString *encodedString = [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return encodedString;
}

@end


@implementation NSString (Trim)
//去空格只局限于首尾空格
- (NSString *)trimBothEnd {
    NSMutableCharacterSet* emptyStringSet = [[NSMutableCharacterSet alloc] init];
    [emptyStringSet formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [emptyStringSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"　"]];
    NSString *string = [self stringByTrimmingCharactersInSet:emptyStringSet];
    return string;
}
//去掉字符串中所有的空格
- (NSString *)trimSpace {
    NSString *string = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    return string;
}

- (NSString *)trimInnerReturn {
    NSString *string = self;
    string = [self stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return string;
}

- (NSString *)trimNewlinesToOne {
    if (![self isNonEmpty]) {
        return @"";
    }
    NSError *error = nil;
    NSRegularExpression *exp = [[NSRegularExpression alloc] initWithPattern:@"\n+" options:0 error:&error];
    if (error != nil) {
        return self;
    }
    NSString *result = [exp stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, self.length) withTemplate:@"\n"];
    return result;
}

+ (NSString *)stringWithBase64EncodedString:(NSString *)string
{
    NSData *data = [NSData dataWithBase64EncodedString:string];
    if (data)
    {
        return [[self alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedStringWithWrapWidth:wrapWidth];
}

- (NSString *)base64EncodedString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedString];
}

- (NSString *)base64DecodedString
{
    return [NSString stringWithBase64EncodedString:self];
}

- (NSData *)base64DecodedData
{
    return [NSData dataWithBase64EncodedString:self];
}

@end
