package org.kne.cloud.network.klalb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class DatagramKLALBPacketLink implements KLALBPacketLink {

	@Override
	public String toString() {
		return "DatagramKLALBPacketLink [ds=" + ds + "]";
	}

	private DatagramSocket ds;

	public DatagramKLALBPacketLink(DatagramSocket connectDatagramSocket) throws IOException {
		this.ds=connectDatagramSocket;
	}

		private ByteArrayOutputStream bos=new ByteArrayOutputStream(65535);
		private DataOutputStream dos=new DataOutputStream(bos);
	@Override
	public void writePacket(KLALBPacket kp) throws IOException {
		//System.out.println("               TX:"+kp);
		bos.reset();
		KLALBOutputStream.writeKLALBPacketToStream(dos, kp);
		byte[]bt=bos.toByteArray();
		DatagramPacket dp=new DatagramPacket(bt,bt.length);
		ds.send(dp);
	}

	private byte[]bc=new byte[65535];
	@Override
	public KLALBPacket readPacket() throws IOException {
		DatagramPacket dp=new DatagramPacket(bc, bc.length);
		ds.receive(dp);
		DataInputStream dis=new DataInputStream(new ByteArrayInputStream(bc, 0, dp.getLength()));
		KLALBPacket kp=KLALBInputStream.readKLALBPacketFromStream(dis);
		dis.close();
		//System.out.println("               RX:"+kp);
		return kp;
	}

	@Override
	public void close() throws IOException {
		ds.close();
	}

	@Override
	public boolean isClosed() {
		return ds.isClosed();
	}

	@Override
	public void setSoTimeout(int val) throws SocketException  {
		ds.setSoTimeout(val);
	}

	@Override
	public int getSoTimeout() throws SocketException {
		return	ds.getSoTimeout();
	}
}
