package fr.upem.net.udp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by carayol on 04/02/15.
 */
public abstract class Requester {

    private DatagramChannel dc;
    private InetSocketAddress serverAddress;

    public Requester(InetSocketAddress serverAddress){
        this.serverAddress=serverAddress;
    }

	/**
     * Create and return the String represented by the ByteBuffer bb 
     * in the following representation:
     * - the size (as an Big Indian int) of the charsetName encoding in ASCII<br/>
     * - the bytes encoding this charsetName in ASCII<br/>
     * - the bytes encoding the message in this charsetName.<br/>
     * The accepted ByteBuffer buffer must be in <strong>write mode</strong> 
     * (need to be flipped before to be used).
	 * 
	 * @param bb a ByteBuffer containing the representation of a message
	 * @return the String represented by bb
	 */
    public static String decodeString(ByteBuffer bb) {
      // TODO
    }

    /**
     * Create and return a new ByteBuffer containing the representation of msg
     * string using the charset charsetName in the following format.
     * - the identifier of the request as a Big Endian long  
     * - the size (as an Big Indian int) of the charsetName encoding in ASCII<br/>
     * - the bytes encoding this charsetName in ASCII<br/>
     * - the bytes encoding msg in charsetName.<br/>
     * The returned ByteBuffer is in <strong>write mode</strong> (need to be flipped
     * before to be used).
     * @param requestNumber the identifier
     * @param msg the String to send 
     * @param charsetName name of the Charset to encode the String msg
     * @return a newly allocated ByteBuffer containing the representation of msg
     */
    protected ByteBuffer createPacket(long requestNumber,String msg,Charset cs){
      // TODO
    }

    protected void send(ByteBuffer buff) throws IOException {
        dc.send(buff,serverAddress);
    }

    protected void receive(ByteBuffer buff) throws IOException {
        dc.receive(buff);
    }

    public void open() throws IOException {
        if (dc!=null) 
        	throw new IllegalStateException("Requester already opened.");
        dc=DatagramChannel.open();
        dc.bind(null);
    }

    public void close() throws IOException {
        if (dc==null) 
        	throw new IllegalStateException("Requester was never opened.");
        dc.close();
    }

    public abstract List<String> toUpperCase(List<String> list,Charset cs) throws IOException,InterruptedException;

}