package com.ht.data;

import java.nio.ByteBuffer;
import java.util.logging.Logger;


public class DataValueUtil {
	private static final Logger log = Logger.getLogger(DataValueUtil.class.getName());
	
	/**
	 * 比较两个数据是否相等
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static double compare(Object v1, Object v2) {
		if (v1 instanceof Number && v2 instanceof Number) {
			return ( (Number)v1 ).doubleValue() - ( (Number)v2 ).doubleValue();
		} else {
			return v1.equals(v2) ? 0 : 1;
		}
	}
	
	public static byte[] getDataBytes(Object obj) {
		log.finer("encode Data:" + obj);
		
		if (obj instanceof Integer) {
			return intToBytes((Integer) obj);
		} else if (obj instanceof Long) {
			return longToBytes((Long) obj);
		} else if (obj instanceof Float) {
			return floatToBytes((Float) obj);
		} else if (obj instanceof Double) {
			return doubleToBytes((Double) obj);
		} else if (obj instanceof Boolean) {
			return obj.toString().getBytes();
		} else if (obj instanceof String) {
			return ((String)obj).getBytes();
		} else if (obj instanceof byte[]) {
			return (byte[])obj;
		}
		
		return null;
	}
	
	public static Object getDataValue(byte[] data, TagDataType dataType) {
		log.finer("decode Data:" + dataType);
		
		switch (dataType) {
		case BOOL:// 布尔
			return Boolean.parseBoolean(new String(data));
		case STRING:// 字符串
			return new String(data);
		case INT:// 整数
			return bytesToInt(data);
		case LONG:// 整数
			return bytesToLong(data);
		case FLOAT:// 小数
			return bytesToFloat(data);
		case DOUBLE:
			return bytesToDouble(data);
		case BIN: 
			return data;
		default:
			break;
		}
		return null;
	}

	public static byte[] intToBytes(int num) {
		
		ByteBuffer buf = ByteBuffer.allocate(4);

		buf.putInt(num);

		return buf.array();
		
	}

	public static int bytesToInt(byte[] temp) {
		
		ByteBuffer buf = ByteBuffer.allocate(4);

		buf.put(temp);
		
		buf.flip();
		
		return buf.getInt();
		
	}
	
	
	public static byte[] longToBytes(long num) {
		
		ByteBuffer buf = ByteBuffer.allocate(8);

		buf.putLong(num);

		return buf.array();
		
	}

	public static long bytesToLong(byte[] temp) {
		
		ByteBuffer buf = ByteBuffer.allocate(8);

		buf.put(temp);
		
		buf.flip();
		
		return buf.getLong();
		
	}

	public static byte[] floatToBytes(float f) {

		ByteBuffer buf = ByteBuffer.allocate(4);

		buf.putFloat(f);

		return buf.array();

	}

	public static float bytesToFloat(byte[] temp) {

		ByteBuffer buf = ByteBuffer.allocate(4);

		buf.put(temp);
		
		buf.flip();

		return buf.getFloat();

	}
	
	public static byte[] doubleToBytes(double d) {

		ByteBuffer buf = ByteBuffer.allocate(8);

		buf.putDouble(d);

		return buf.array();

	}

	public static double bytesToDouble(byte[] temp) {

		ByteBuffer buf = ByteBuffer.allocate(4);

		buf.put(temp);

		buf.flip();
		
		return buf.getDouble();

	}
	
}
