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

/** Representation of payload for list response.
 * @author	Louis Royer
 * @author	Flavien Haas
 * @author	JS Auge
 * @version	1.0
 */
public class FileList extends Payload {
	private String[] fileList;

	/** Constructor (typically used by the server) with an ArrayList parameter containing
	 * filenames.
	 * @param fileList	a list of files. Must not be empty.
	 * @throws	InternalError
	 */
	public FileList(String[] fileList) throws InternalError {
		super(RequestResponseCode.LIST_RESPONSE);
		/* assert to help debugging */
		assert fileList.length != 0 : "Payload size of FileList must not be empty, use EmptyDirectory from Payload instead";
		if (fileList.length == 0) {
			throw new InternalError();
		}
		this.fileList = fileList;
	}

	/** Constructor (typically used by client) with a byte[] parameter containing the Packet received.
	 * @param packet	the full packet received
	 * @throws	SizeError
	 * @throws	InternalError
	 * @throws	ProtocolError
	 * @throws	TransmissionError
	 */
	protected FileList(byte[] packet) throws TransmissionError, SizeError, ProtocolError, InternalError {
		super(packet);
		/* assert to help debugging */
		assert requestResponseCode == RequestResponseCode.LIST_RESPONSE : "FileList subclass is incompatible with this Packet, request/response code must be checked before using this constructor";
		/* InternalErrorException */
		if (requestResponseCode!= RequestResponseCode.LIST_RESPONSE) {
			throw new InternalError();
		}
		int size = getPayloadSize(packet);
		fileList = BytesArrayTools.readStringArray(packet, PAYLOAD_START_POSITION, size, "\n");
	}

	/** 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 size
		int size = PAYLOAD_START_POSITION + BytesArrayTools.computeStringArraySize(fileList, "\n");
		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 fileList
		BytesArrayTools.write(packet, fileList, PAYLOAD_START_POSITION, "\n");
		return packet;
	}

	/** fileList getter.
	 * @return	fileList
	 */
	public String[] getFileList() {
		return fileList;
	}
}
