//
//  Data.m
//  SFS2X
//
//  Original development by Infosfer Game Technologies Ltd. | http://www.infosfer.com.
//
//  Maintained and developed by A51 Integrated.
//  Copyright 2012 A51 Integrated | http://a51integrated.com. All rights reserved.
//

#import "Data.h"


@implementation Data


-(id)initWithData:(NSData *)anotherData {
	if ((self = [super init])) {
		_data = (NSMutableData *)anotherData;
	}
	return self;
}

+(id)dataWithData:(NSData *)anotherData {
	Data *newInstance = [[Data alloc] initWithData:anotherData];
	return newInstance;
}



-(void)decreasePosition {
	_dataPosition--;
}

-(BOOL)readBool {
	uint8_t intV;
	NSRange range = {_dataPosition, 1};
	[_data getBytes:&intV range:range];
	_dataPosition++;
	return !(intV == 0);
}

-(uint8_t)readByte {
	uint8_t intV;
	NSRange range = {_dataPosition, 1};
	[_data getBytes:&intV range:range];
	_dataPosition++;
	return intV;
}

-(int16_t)readShort {
	int16_t intV;
	NSRange range = {_dataPosition, 2};
	[_data getBytes:&intV range:range];
	intV = CFSwapInt16(intV);
	_dataPosition += 2;
	return intV;
}

-(int)readInt{
	
	int32_t intV;
	NSRange range = {_dataPosition, 4};
	[_data getBytes:&intV range:range];
	intV = CFSwapInt32(intV);
	_dataPosition += 4;
	
	return intV;
}

-(long long)readLong {
	int64_t intV;
	NSRange range = {_dataPosition, 8};
	[_data getBytes:&intV range:range];
	intV = CFSwapInt64(intV);
	_dataPosition += 8;
	
	return intV;
}

-(float)readFloat {
	uint32_t floatV;
	NSRange range = {_dataPosition, 4};
	[_data getBytes:&floatV range:range];
	_dataPosition += 4;
	floatV = CFSwapInt32(floatV);
	uint8_t *p = (uint8_t *)&floatV;
	
	float f;
	uint8_t *fp = (uint8_t *)&f;
	
	for (int i = 0; i < 4; i++) {
		*(fp++) = *(p++);
	}
	
	return f;
}

-(double)readDouble {
	uint64_t doubleV;
	NSRange range = {_dataPosition, 8};
	[_data getBytes:&doubleV range:range];
	_dataPosition += 8;
	doubleV = CFSwapInt64(doubleV);
	uint8_t *p = (uint8_t *)&doubleV;
	
	double d;
	uint8_t *fp = (uint8_t *)&d;
	
	for (int i = 0; i < 8; i++) {
		*(fp++) = *(p++);
	}
	
	return d;
}

-(NSString *)readUTF {
	
	uint16_t length;
	NSRange strRange = {_dataPosition, 2};
	[_data getBytes:&length range:strRange];
	length = CFSwapInt16(length);
	_dataPosition += 2;
	
	char charBuffer[length + 1];
	NSRange range = {_dataPosition, length};
	[_data getBytes:charBuffer range:range];
	charBuffer[length] = 0;
	_dataPosition += length;
	
	return [NSString stringWithCString:charBuffer encoding:NSUTF8StringEncoding];
	
}

-(NSData *)readDataWithLength:(int)len {
	NSRange range = {_dataPosition, len};
	
	NSData *data = [_data subdataWithRange:range];
	_dataPosition += len;
	return data;
}

@end
