package org.kne.cloud.network.klalb;
import static org.kne.cloud.network.klalb.KLALBPacket.*;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamCorruptedException;
import java.net.Inet6Address;

public class KLALBInputStream extends DataInputStream {
	public KLALBInputStream(InputStream in) throws IOException {
		super(in);
		byte[]b=new byte[5];
		readFully(b);
		String s=new String(b,"ascii");
		if(!s.equals("KLALB")) {
			throw new StreamCorruptedException("no KLALB format");
		}
		int bv=readInt();
		int sv=readInt();
		if(bv!=2)
			throw new StreamCorruptedException("remote version is V"+bv+"."+sv+",not V2.0");
	}
	public KLALBPacket readPacket() throws IOException {
		return readKLALBPacketFromStream(this);
	}
	public static KLALBPacket readKLALBPacketFromStream(DataInputStream in) throws IOException {
int type=in.read();
		
		if(type==-1) {
			return null;
		}
		KLALBPacket klp;
		switch(type) {
		case PING:klp=new PINGPacket();
			klp.readFromStream(in);
			return klp;
		case PONG:
			klp=new PONGPacket();
			klp.readFromStream(in);
			return klp;
		case SYNT:
			klp=new SYNTPacket();
			klp.readFromStream(in);
			return klp;
		case SACKT:
			klp=new SACKTPacket();
			klp.readFromStream(in);
			return klp;
		case RST:
			klp=new RSTPacket();
			klp.readFromStream(in);
			return klp;
		case DATAT:
			klp=new DATATPacket();
			klp.readFromStream(in);
			return klp;
		case ACKT:
			klp=new ACKTPacket();
			klp.readFromStream(in);
			return klp;
		case VADDR:
			klp=new VADDRPacket();
			klp.readFromStream(in);
			return klp;
		case ADDLINES:
			klp=new ADDLINESPacket();
			klp.readFromStream(in);
			return klp;
		case NACKT:
			klp=new NACKTPacket();
			klp.readFromStream(in);
			return klp;	
			case TEST:
				klp=new TESTPacket();
				klp.readFromStream(in);
				return klp;
			case VADDRACK:
				klp=new VADDRACKPacket();
				klp.readFromStream(in);
				return klp;
			case VADDRREQ:
				klp=new VADDRREQPacket();
				klp.readFromStream(in);
				return klp;
		}
		throw new StreamCorruptedException("unknown package type:"+type);
	}
}
