//
//  NSString+convert.m
//  ZigBeeGatewayPublic
//
//  Created by coderYK on 2018/9/5.
//  Copyright © 2018年 coderYK. All rights reserved.
//

#import "NSString+convert.h"

@implementation NSString (convert)

- (int)rds_intValueFromHexString{
    
    int value = (int)[self rds_uintegerValueFromHexString];
    return value;
}

- (NSUInteger)rds_uintegerValueFromHexString {
    
    NSString *hexString = [NSString stringWithFormat:@"%@", self]; // 防止类型不对
    if (hexString.length%2) {
        hexString = [NSString stringWithFormat:@"0%@", hexString];
    }
    return strtoul([hexString UTF8String], NULL, 16);
}

- (NSString *)rds_decimalFromHexString{
    
    NSString *hexString = [NSString stringWithFormat:@"%@", self]; // 防止类型不对
    if (hexString.length%2) {
        hexString = [NSString stringWithFormat:@"0%@", hexString];
    }
    
    NSString *result = [NSString stringWithFormat:@"%lu",strtoul([hexString UTF8String], 0, 16)];
    return result;
}

- (NSUInteger)rds_uintegerValueFromBinaryString {
    
    NSString *bString = [NSString stringWithFormat:@"%@", self]; // 防止类型不对
    if (bString.length%2) {
        bString = [NSString stringWithFormat:@"0%@", bString];
    }
    return strtoul([bString UTF8String], NULL, 2);
}

- (NSInteger)rds_numberWithHexString{
    
    const char *hexChar = [self cStringUsingEncoding:NSUTF8StringEncoding];
    
    int hexNumber;
    
    sscanf(hexChar, "%x", &hexNumber);
    
    return (NSInteger)hexNumber;
}

- (NSString *)rds_getHexFromDecimal{
    
    NSString *decimalString = [NSString stringWithFormat:@"%@", self]; // 防止类型不对
    NSString *result = [NSString stringWithFormat:@"%02x",decimalString.intValue];
    if (result.length == 3) {
        result = [NSString stringWithFormat:@"0%@",result];
    }
    return result;
}

// 将十进制转化为十六进制
+ (NSString *)rds_getHexByDecimal:(int)decimal{
    NSString *nLetterValue;
    NSString *str =@"";
    int number;
    for (int i = 0; i<9; i++) {
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number){
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",number];
        }
        str = [nLetterValue stringByAppendingString:str];
        if (decimal == 0) {
            break;
        }
    }
    //不够一个字节凑 补0
    if (str.length % 2 != 0){
        str = [NSString stringWithFormat:@"0%@",str];
    }
    
    return str;
}

- (NSString *)rds_stringFromHexString {
    
    NSString *hexString = self;
    NSUInteger count = hexString.length/2;
    char *buffer = malloc(count+1);
    if (buffer == NULL) return nil;
    
    for (int i=0; i<count; i++) {
        // 0211 6c 6f 76 65 79 6f 75 62 11 76 84 5f c3 90 fd 00 01
        NSUInteger value = [[hexString substringWithRange:NSMakeRange(i*2, 2)] rds_uintegerValueFromHexString];
        buffer[i] = value;
    }
    
    NSData *strData = [NSData dataWithBytes:buffer length:count];
    NSString *unicodeString = [[NSString alloc] initWithData:strData encoding:NSUnicodeStringEncoding];
    unicodeString = [NSString stringWithCString:[unicodeString UTF8String] encoding:NSUTF8StringEncoding]; // 去掉 unicodeString 后面多余的\0
    free(buffer);
    buffer = NULL;
    return unicodeString;
}

// ascii码十六进制转换为普通字符串的。
- (NSString *)rds_stringFromAsciiHexString {
    NSString *hexString = self;
    hexString = [hexString stringByReplacingOccurrencesOfString:@"ff" withString:@""];// 删除用于补位的f
    if (kNULLString(hexString)) {
        return @"";
    }
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        
        NSString * hexCharStr;
        if (hexString.length >= i + 2) {
            hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        }else{
            DDLog(@"ascii码十六进制转换为普通字符串的出错");
            return nil;
        }
        
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //DDLog(@"\n%@\n%@", hexString, unicodeString);
    if (kNULLString(unicodeString)) {
        unicodeString = @"";
    }
    return unicodeString;
}

//普通字符串转换为ascii码十六进制的。
- (NSString *)rds_stringToAsciiHexString{
    NSString *string = self;
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

- (NSString *)rds_stringToAsciiString{
    NSString *string = self;
    NSMutableString *mustring = [[NSMutableString alloc] init];
    const char *ch = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if(!ch) return nil;
    for (int i = 0; i < strlen(ch); i++) {
        [mustring appendString:[NSString stringWithFormat:@"%x", ch[i]]];
    }
    return mustring;
}

- (NSString *)rds_binaryStringReversed {
    // 逆序
    NSString *binaryString = self;
    unsigned long len;
    len = [binaryString length];
    unichar a[len];
    for(int i = 0; i < len; i++)
    {
        unichar c = [binaryString characterAtIndex:len-i-1];
        a[i] = c;
    }
    NSString *orderBinaryString= [NSString stringWithCharacters:a length:len];
    
    return orderBinaryString;
}

- (NSArray *)rds_indexArrayFromexIDString {
    
    NSString *hexIDString = self;
    NSString *bString = [hexIDString rds_getBinaryFromHex];
    return [bString rds_indexArrayFromBinaryString];
}

- (NSArray *)rds_indexArrayFromBinaryString {
    NSString *binaryIDString = self;
    NSMutableString *reverseStr = [binaryIDString rds_binaryStringReversed];
    NSMutableArray *tempArr = [NSMutableArray array];
    for (int i = 0; i < reverseStr.length; i++) {
        if ([reverseStr characterAtIndex:i] == 49) {
            [tempArr addObject:@(i)];
        }
    }
    return [tempArr copy];
}

- (NSString *)rds_getBinaryFromHex {
    
    NSString *hex = self;
    NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
    hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"a"];
    [hexDic setObject:@"1011" forKey:@"b"];
    [hexDic setObject:@"1100" forKey:@"c"];
    [hexDic setObject:@"1101" forKey:@"d"];
    [hexDic setObject:@"1110" forKey:@"e"];
    [hexDic setObject:@"1111" forKey:@"f"];
    
    NSMutableString *binaryString=[[NSMutableString alloc] init];
    
    for (int i=0; i<[hex length]; i++) {
        NSRange rage;
        rage.length = 1;
        rage.location = i;
        NSString *key = [hex substringWithRange:rage];
        binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
    }
    return binaryString;
}

- (NSString *)rds_getHexByBinary {
    
    //    NSString *dec = [self getDecimalByBinary:binary];
    //    NSString *hex = [self getHexByDecimal:dec];
    
    NSString *binary = self;
    NSMutableDictionary *binaryDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [binaryDic setObject:@"0" forKey:@"0000"];
    [binaryDic setObject:@"1" forKey:@"0001"];
    [binaryDic setObject:@"2" forKey:@"0010"];
    [binaryDic setObject:@"3" forKey:@"0011"];
    [binaryDic setObject:@"4" forKey:@"0100"];
    [binaryDic setObject:@"5" forKey:@"0101"];
    [binaryDic setObject:@"6" forKey:@"0110"];
    [binaryDic setObject:@"7" forKey:@"0111"];
    [binaryDic setObject:@"8" forKey:@"1000"];
    [binaryDic setObject:@"9" forKey:@"1001"];
    [binaryDic setObject:@"A" forKey:@"1010"];
    [binaryDic setObject:@"B" forKey:@"1011"];
    [binaryDic setObject:@"C" forKey:@"1100"];
    [binaryDic setObject:@"D" forKey:@"1101"];
    [binaryDic setObject:@"E" forKey:@"1110"];
    [binaryDic setObject:@"F" forKey:@"1111"];
    
    if (binary.length % 4 != 0) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 4 - binary.length % 4; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    NSString *hex = @"";
    for (int i=0; i<binary.length; i+=4) {
        
        NSString *key = [binary substringWithRange:NSMakeRange(i, 4)];
        NSString *value = [binaryDic objectForKey:key];
        if (value) {
            
            hex = [hex stringByAppendingString:value];
        }
    }
    
    return hex;
}

- (NSString *)rds_filterUnfitCharactor {
    
    NSString *filterText = self;
    NSError *error = NULL;
    NSString *regexStr = @"[^a-zA-Z0-9\u4e00-\u9fa5]";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
    return result;
}

- (NSString *)rds_stringTohexString {
    NSString *string = self;
    
//    // 一个汉字2字节
//
//    NSMutableString *strM = [NSMutableString string];
//    for (int i=0; i<string.length; i++) {
//        NSString *code = [NSString stringWithFormat:@"%04x", [string characterAtIndex:i]];
//        [strM appendString:code];
//    }
//    return strM;
    
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++){
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;

}

- (NSString *)rds_getAsciiHexStringFromStringByte:(NSUInteger)byte {
    
    NSString *hexName = [self rds_stringToAsciiHexString];
    int offset = (int)(byte*2 - hexName.length);
    for (int i = 0; i < offset; i++) {
        hexName = [NSString stringWithFormat:@"%@f",hexName];
    }
    return hexName;
}

+ (NSString *)rds_ChineseNumFrom:(NSUInteger)number {
    
    static NSNumberFormatter *formatter;
    if (formatter == nil) {
        formatter = [[NSNumberFormatter alloc] init];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        formatter.numberStyle = kCFNumberFormatterSpellOutStyle;//kCFNumberFormatterRoundHalfDown;
    }
    
    return [formatter stringFromNumber:[NSNumber numberWithUnsignedInteger:number]];
}


- (NSString *)rds_utf8ToUnicode{
    NSString *string = self;
    NSUInteger length = [string length];
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++){
        NSMutableString *s = [NSMutableString stringWithCapacity:0];
        unichar _char = [string characterAtIndex:i];
        // 判断是否为英文和数字
        if (_char <= '9' && _char >='0'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='a' && _char <= 'z'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='A' && _char <= 'Z')
        {
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else{
            // 中文和字符
            [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
            // 不足位数补0 否则解码不成功
            if(s.length == 4) {
                [s insertString:@"00" atIndex:2];
            } else if (s.length == 5) {
                [s insertString:@"0" atIndex:2];
            }
        }
        [str appendFormat:@"%@", s];
    }
    str = [str stringByReplacingOccurrencesOfString:@"\\u" withString:@""];
    return str;
}


+ (NSString *)rds_stringFromDict:(NSDictionary *)dict{
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

- (NSData *)rds_getDataFromString{
    NSData *data =[self dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

- (NSData *)rds_getDataFromHexString{
    
    NSString *string = self;
    
    NSMutableData* data = [NSMutableData data];
    int idx;
    for (idx = 0; idx+2 <= string.length; idx+=2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [string substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}

+ (NSString *)rds_getHexStringFromData:(NSData *)data{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}


+ (NSString *)rds_getHexStringFromNSData:(NSData *)data{
    
    return [[[[NSString stringWithFormat:@"%@",data]
              stringByReplacingOccurrencesOfString:@"<" withString:@""]
             stringByReplacingOccurrencesOfString:@">" withString:@""]
            stringByReplacingOccurrencesOfString:@" " withString:@""];
}

+ (NSString *)rds_getStringFromData:(NSData *)data{
    NSString *result =[[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result;
}

// 大小端
- (NSString *)rds_changeLittleEndian{
    
    // 大端转成小端
    NSString *tmpStr = self;
    NSMutableArray *tmpArra = [NSMutableArray array];
    for (int i = 0 ; i<tmpStr.length ;i+=2) {
        NSString *str = [tmpStr substringWithRange:NSMakeRange(i, 2)];
        [tmpArra addObject:str];
    }
        
    NSArray *lastArray = [[tmpArra reverseObjectEnumerator] allObjects];
    NSMutableString *lastStr = [NSMutableString string];
    for (NSString *str in lastArray) {
        [lastStr appendString:str];
    }
    
    return lastStr.copy;
}

- (NSString *)addZeroWithLength:(int)length{
    
    NSString *string = nil;
    NSString *orgStr = self;
    if (kNULLString(orgStr)) {
        orgStr = @"";
    }

    if (orgStr.length<length) {
        NSUInteger inter = length-orgStr.length;
        for (int i=0;i< inter; i++) {
            string = [NSString stringWithFormat:@"%@*",orgStr];
            orgStr = string;
        }
    }
    return orgStr;
}

- (NSString *)rds_changeFistUppercase{
    
    NSString *dealString = self;
    NSString *resultString = @"";
    
    if (dealString.length > 0) {
        resultString = [dealString stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[dealString substringToIndex:1] capitalizedString]];
        //lowercaseString
        resultString = [resultString stringByReplacingCharactersInRange:NSMakeRange(1,dealString.length-1) withString:[[dealString substringFromIndex:1] lowercaseString]];
        
    }
    
    return resultString;
}

+ (NSString*)rds_dicToJson:(NSDictionary *)dic
{
 
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

+ (NSDictionary *)rds_jsonToDic:(NSString *)json{
    if (json == nil){
        return nil;
    }
    
    //所有控制符都会被替换成空字符。
    NSString *jsonString =[json stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
    if (error){
        NSLog(@"json格式string解析失败:%@",error);
        return nil;
    }
    
    return dict;
}
@end
