package org.kne.cloud.network.kltp;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import org.kne.cloud.network.ByteBufferAllocator;
import org.kne.cloud.network.NetworkPacket;
import org.kne.cloud.network.klalb.PortPacket;
import org.kne.io.KNEChannels;

public class KLTPSessionPacket extends NetworkPacket implements PortPacket{
	private static final int KLTP_SESSION_HEADER_LENGTH=8;
	private ByteBuffer header=NetworkPacket.bufferAllocator.allocate(KLTP_SESSION_HEADER_LENGTH);
	

	private KLTPInputStream inputstream;
	public KLTPSessionPacket(int sport, int dport,KLTPInputStream inputstream) {
		setSrcPort(sport);
		setDstPort(dport);
		this.inputstream=inputstream;
	}
	public KLTPSessionPacket(int sport, int dport) {
		setSrcPort(sport);
		setDstPort(dport);
	}
	public KLTPSessionPacket() {
		
	}
	

	public KLTPSessionPacket(KLTPInputStream inputstream) {
		super();
		this.inputstream = inputstream;
	}
	public KLTPInputStream getInputstream() {
		return inputstream;
	}

	@Override
	public long getTotalLength() {
		return KLTP_SESSION_HEADER_LENGTH;
	}

	@Override
	public void writeToChannel(WritableByteChannel dto) throws IOException {
		dto.write(header.slice(0, KLTP_SESSION_HEADER_LENGTH));
		//System.out.println("writesession:"+header);
	}

	@Override
	public void readFromChannel(ReadableByteChannel din, long length) throws IOException {
		header.limit(KLTP_SESSION_HEADER_LENGTH);
		KNEChannels.readFully(din, header);
		header.flip();
		//System.out.println("readsesion:"+header);
	}

	
	
	@Override
	public int hashCode() {
		return getSrcPort()^getDstPort();
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		KLTPSessionPacket other = (KLTPSessionPacket) obj;
		
		return (getSrcPort()==other.getSrcPort())&&(getDstPort()==other.getDstPort());
	}
	@Override
	protected boolean needEndPosition() {
		return false;
	}

	public void setSrcPort(int sport) {
		header.putInt(0,sport);
	}
	
	public void setDstPort(int dport) {
		header.putInt(4,dport);
	}
	
	@Override
	public int getSrcPort() {
		return header.getInt(0);
	}

	@Override
	public int getDstPort() {
		return header.getInt(4);
	}
	@Override
	public String toString() {
		return "KLTPSession "+getSrcPort()+"->"+getDstPort();
	}

}
