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

/** Representation of payload for denied response.
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class Denied extends Payload {
	private String filename;
	private long offset;
	static final private int OFFSET_POSITION = PAYLOAD_START_POSITION;
	static final private int FILENAME_POSITION = OFFSET_POSITION + 8;

	/** Constructor (typically used by server) with informations about file part to send as parameters.
	 * @param filename	name of the file to send
	 * @param offset	where in the file begins the part we are sending
	 * @throws	InternalError
	 */
	public Denied(String filename, long offset) throws InternalError {
		super(RequestResponseCode.DENIED);
		/* asserts to help debugging */
		assert offset >= 0 : "offset cannot be negative";
		assert filename != null : "filename is required";
		if (offset < 0 || filename == null) {
			throw new InternalError();
		}
		this.filename = filename;
		this.offset = offset;
	}

	/** Constructor (typically used by client) with Packet received as parameter.
	 * @param packet	the full Packet received
	 * @throws	SizeError
	 * @throws	InternalError
	 * @throws	TransmissionError
	 */
	protected Denied(byte[] packet) throws TransmissionError, SizeError, ProtocolError, InternalError {
		super(packet);
		int filenameSize = getPayloadSize(packet) - FILENAME_POSITION + PAYLOAD_START_POSITION;
		offset = BytesArrayTools.readLong(packet, OFFSET_POSITION);
		filename = BytesArrayTools.readString(packet, FILENAME_POSITION, filenameSize);
	}

	/** 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 {
		// compute total size
		int size = FILENAME_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 offset to Packet
		BytesArrayTools.write(packet, OFFSET_POSITION, offset);
		// write filename to Packet
		BytesArrayTools.write(packet, filename, FILENAME_POSITION);
		return packet;
	}

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

	/** offset getter.
	 * @return	offset
	 */
	public long getOffset() {
		return offset;
	}
}
