package org.kne.cloud.network.klalb;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;

public class KLALBUtils {
	public static Inet6Address uuidToIP(UUID uuid) {
		ByteArrayOutputStream bos=new ByteArrayOutputStream(8);
		DataOutputStream dos=new DataOutputStream(bos);
		try {
		dos.writeLong(uuid.getMostSignificantBits());
			dos.writeLong(uuid.getLeastSignificantBits());
		dos.close();} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		try {
			return (Inet6Address) Inet6Address.getByAddress(bos.toByteArray());
		} catch (UnknownHostException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args) {
		System.out.println(uuidToIP(new UUID(-1,-1)));
	}
	public static String bytesUnit(long v) {
		if(v>=1024L*1024*1024*1024*1024) {
			return format( v/(1024.0*1024.0*1024.0*1024.0*1024.0))+"P";
		}else if(v>=1024L*1024*1024*1024) {
			return format (v/(1024.0*1024.0*1024.0*1024.0))+"T";
		}else if(v>=1024L*1024*1024) {
			return format( v/(1024.0*1024.0*1024.0))+"G";
		}else if(v>=1024L*1024) {
			return format( v/(1024.0*1024.0))+"M";
		}else if(v>=1024L) {
			return format( v/(1024.0))+"K";
		}else  {
			return v+"B";
		}
	}
	private static String format( double d) {
	String fmt=String.format( "%.2f",d);
	if(fmt.length()>4) {
		fmt=fmt.substring(0, 4);
	}
	if(fmt.endsWith(".")) {
		fmt=fmt.substring(0, fmt.length()-1);
	}
		return fmt;
	}
	public static int binarySearchDATATPacketNumber(List<DATATPacket>lst,long number) {
		int low =0;
		int high=lst.size()-1;
		int middle=0;
		if(low>high||number<lst.get(low).getNumber()||number>lst.get(high).getNumber()) {
			return -1;
		}
		while(low<=high) {
			middle=(low+high)/2;
			long xn=lst.get(middle).getNumber();
			if(xn>number) {
				high=middle-1;
			}else if(xn<number) {
				low=middle+1;
			}else {
				return middle;
			}
		}
		return -1;
	}
}
