package jp.progressive.rudp;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

import org.apache.commons.lang3.Pair;

/**
 * スレッドセーフ
 */
class UdpSocket implements Closeable {
    private DatagramChannel channel;
    private ByteBuffer readBuffer;

    public UdpSocket() {
	this.channel = null;
	this.readBuffer = ByteBuffer.allocateDirect(65536);
    }

    public void open(int port) throws IOException {
	channel = DatagramChannel.open();
	channel.socket().setReuseAddress(true);
	channel.socket().bind(new InetSocketAddress(port));
	channel.configureBlocking(true);
    }

    public boolean isOpen() {
	return channel.isOpen();
    }

    public void send(ByteBuffer buffer, SocketAddress address)
	    throws IOException {
	channel.send(buffer, address);
    }

    public Pair<SocketAddress, ByteBuffer> receive() throws IOException {
	readBuffer.clear();
	SocketAddress remote = channel.receive(readBuffer);
	readBuffer.flip();
	return new Pair<SocketAddress, ByteBuffer>(remote, readBuffer);
    }

    public void close() throws IOException {
	channel.close();
    }
}
