//
//  KLTFormat.m
//  KaiLiTe
//
//  Created by boosal on 2016/9/12.
//  Copyright © 2016年 boosal. All rights reserved.
//

#import "KLTFormat.h"

@implementation KLTFormat


//--------------- byte 和hexString 相互转换 ------------------

//在和硬件之间的数据发送和接受，用的都是byte数组。
/*
+ (NSData *) hexStringToData:(NSString *)hexString
{
    int j = 0;
    Byte bytes[[hexString length]];
    ///3ds key的Byte 数组， 128位
    for(int i=0; i<[hexString length]; i++)
    {
        int int_ch;  // 两位16进制数转化后的10进制数
        
        unichar hex_char1 = [hexString characterAtIndex:i]; //两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   // 0 的Ascii - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; // A 的Ascii - 65
        else
            int_ch1 = (hex_char1-87)*16; // a 的Ascii - 97
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; //两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); // 0 的Ascii - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; // A 的Ascii - 65
        else
            int_ch2 = hex_char2-87; // a 的Ascii - 97
        
        int_ch = int_ch1+int_ch2;
        bytes[j] = int_ch;  //将转化后的数放入Byte数组里
        j++;
    }
    
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)/sizeof(bytes[0])];
    
    return newData;
}
*/



/**
 *    @brief    将字符表示的16进制数转化为二进制数据
 *    @param     hexString     字符表示的16进制数，长度必须为偶数
 *    @return    二进制数据
 */
+ (NSData *)dataWithHexString:(NSString *)hexString {
    // hexString的长度应为偶数
    if ([hexString length] % 2 != 0)
        return nil;
    
    NSUInteger len = [hexString length];
    NSMutableData *retData = [[NSMutableData alloc] init];
    const char *ch = [[hexString dataUsingEncoding:NSASCIIStringEncoding] bytes];
    for (int i=0 ; i<len ; i+=2) {
        int height=0;
        if (ch[i]>='0' && ch[i]<='9')
            height = ch[i] - '0';
        else if (ch[i]>='A' && ch[i]<='F')
            height = ch[i] - 'A' + 10;
        else if (ch[i]>='a' && ch[i]<='f')
            height = ch[i] - 'a' + 10;
        else
            // 错误数据
            return nil;
        
        int low=0;
        if (ch[i+1]>='0' && ch[i+1]<='9')
            low = ch[i+1] - '0';
        else if (ch[i+1]>='A' && ch[i+1]<='F')
            low = ch[i+1] - 'A' + 10;
        else if (ch[i+1]>='a' && ch[i+1]<='f')
            low = ch[i+1] - 'a' + 10;
        else
            // 错误数据
            return nil;
        
        int byteValue = height*16 + low;
        [retData appendBytes:&byteValue length:1];
    }
    
    return retData;
}

+ (NSString *)dataToHexString:(NSData *)data isReverse:(BOOL)isReverse {
    NSUInteger          len = [data length];
    char *              chars = (char *)[data bytes];
    NSMutableString *   hexString = [[NSMutableString alloc] init];
    
    if (isReverse) {
        for(NSInteger i = len - 1; i >= 0; i-- )
            [hexString appendString:[NSString stringWithFormat:@"%0.2hhX", chars[i]]];
    } else {
        for(NSUInteger i = 0; i < len; i++ )
            [hexString appendString:[NSString stringWithFormat:@"%0.2hhX", chars[i]]];
    }
    
    return hexString;
}

- (NSString *)convertDataToHexStr:(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;
}

+ (NSData *)intToData:(int)a {
    Byte bytes[2];
    for (int i = 1; i >= 0; i --) {
        bytes[i] = (Byte)(a & 0xFF);
        a = a >> 8;
    }
    NSData *intData = [[NSData alloc] initWithBytes:bytes length:2];
    
    return intData;
}

+ (NSData *)stringToData:(NSString *)string {
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

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


+ (unsigned long)getIntFromHexString:(NSString *)str {
    //先以16为参数告诉strtoul字符串参数表示16进制数字，然后使用0x%X转为数字类型
    //strtoul如果传入的字符开头是“0x”,那么第三个参数是0也可以
    return strtoul([str UTF8String],0,16);
}



//------------- 当前时间转换成data类型 --------------

+ (NSString *)getDateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_GB"]];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
    return dateString;
}

+ (NSDate *)getDateFromString:(NSString *)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_GB"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter dateFromString:string];
}

+ (NSDate *)getEventDateFromString:(NSString *)string {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_GB"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter dateFromString:string];
}

+ (NSData *)getSystemDateTime {
    Byte dateBytes[7];
    NSDate *current = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:current];
    
    dateBytes[0] = (Byte)((dateComponents.year >> 8));
    dateBytes[1] = (Byte)(dateComponents.year);
    dateBytes[2] = (Byte)(dateComponents.month);
    dateBytes[3] = (Byte)(dateComponents.day);
    
    NSDateComponents *timeComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:current];
    dateBytes[4] = (Byte)(timeComponents.hour);
    dateBytes[5] = (Byte)(timeComponents.minute);
    dateBytes[6] = (Byte)(timeComponents.second);
    
    NSData *dateTimeData = [[NSData alloc] initWithBytes:dateBytes length:7];
    return dateTimeData;
}

+ (NSData *)getSystemDateTimeCT5 {
    Byte dateBytes[6];
    NSDate *current = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc]
                            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:current];
    
    dateBytes[0] = (Byte)(dateComponents.year - 1900);
    dateBytes[1] = (Byte)(dateComponents.month);
    dateBytes[2] = (Byte)(dateComponents.day);
    
    NSDateComponents *timeComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:current];
    dateBytes[3] = (Byte)(timeComponents.hour);
    dateBytes[4] = (Byte)(timeComponents.minute);
    dateBytes[5] = (Byte)(timeComponents.second);
    
    NSData *dateTimeData = [[NSData alloc] initWithBytes:dateBytes length:6];
    return dateTimeData;
}


+ (NSArray *)handleSelfCheckInfo:(NSString *)hex {
    NSMutableArray *array = [NSMutableArray array];
    NSString *h = [hex substringWithRange:NSMakeRange(0, 4)];
    [array addObject: @([self getIntFromHexString:h] * 0.1)];
    NSString *e = [hex substringWithRange:NSMakeRange(4, 4)];
    [array addObject: @([self getIntFromHexString:e] * 0.1)];
    
    for (int i = 8; i < hex.length; i += 2) {
        NSString *x = [hex substringWithRange:NSMakeRange(i, 2)];
        unsigned long temp = [self getIntFromHexString:x];
        switch (i - 8) {
            case 0:
            {
                float temperature = 0.f;
                if ((temp & 0x80) == 0) {
                    
                    temperature = temp + 0.0;
                } else {
                    
                    temperature = (temp) - 0x80 + 0.5;
                }
                [array addObject:@(temperature)];
            }
                break;
            case 2:
            {
                [array addObject: @(temp)];
            }
                break;
                
            default:
                break;
        }
    }
    return array;
}

@end
