package protocolP2P;
import protocolP2P.Payload;
import protocolP2P.RequestResponseCode;
import localException.TransmissionError;
import localException.ProtocolError;
import localException.InternalError;
import localException.SizeError;
import tools.BytesArrayTools;
import tools.HostItem;

/** Representation of payload for load request.
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class SizeRequest extends Payload {
	private String filename;
	/** Constructor (typically used by the client) with a filename parameter.
	 * @param filename	name of the file to download. Must not be empty.
	 */
	public SizeRequest(String filename) throws InternalError {
		super(RequestResponseCode.SIZE_REQUEST);
		/* assert to help debugging */
		assert filename.length() != 0 : "Payload size of LoadRequest must not be empty";
		if (filename.length() == 0) {
			throw new InternalError();
		}
		this.filename = filename;
	}

	/** Constructor (typically used by server) with a byte[] parameter containing the Packet received.
	 * @param packet	the full Packet received
	 * @throws	SizeError
	 * @throws	InternalError
	 * @throws	ProtocolError
	 * @throws	TransmissionError
	 */
	protected SizeRequest(byte[] packet) throws TransmissionError, SizeError, ProtocolError, InternalError {
		super(packet);
		/* Read filename */
		int size = getPayloadSize(packet);
		filename = BytesArrayTools.readString(packet, PAYLOAD_START_POSITION, size);
	}

	/** Returns a byte[] containing Packet with padding.
	 * This Packet is still incomplete and should not be send directly.
	 * ProtocolP2PPacket will use this method to generate the complete Packet.
	 * @return Packet with padding
	 * @throws	InternalError
	 */
	protected byte[] toPacket() throws InternalError {
		int size = PAYLOAD_START_POSITION + filename.length();
		byte[] packet = new byte[size]; // java initialize all to zero
		// set request/response code
		packet[RequestResponseCode.RRCODE_POSITION] = requestResponseCode.codeValue;
		// set Payload size
		setPayloadSize(size - PAYLOAD_START_POSITION, packet);
		// Write filename
		BytesArrayTools.write(packet, filename, PAYLOAD_START_POSITION);
		return packet;
	}

	/** filename getter.
	 * @return	filename
	 */
	public String getFilename() {
		return filename;
	}
}
