package common;

import java.io.IOException;
import java.net.ProtocolException;
import org.xbill.DNS.TXTRecord;

public class ServerPacket extends Packet {

	public ServerPacket(short clientID, byte packetID, byte flags, byte encBase, byte lastPidSeen, byte checksum, byte[] dataContent) {
		super(clientID, packetID, flags, encBase, lastPidSeen, checksum, dataContent);
	}
	
	public ServerPacket(byte[] data) throws ProtocolException {
		super();
		decodePacket(data);
	}

	public static ServerPacket decodeServerPacket(TXTRecord record) throws IOException {
		byte [] decodeStringBytes = (byte[])record.getStringsAsByteArrays().get(0);

		byte [] pktSizeBytes = {0,0};
		int bytesRead = txtConverter.decode(decodeStringBytes, 0, decodeStringBytes.length, 2, pktSizeBytes);
		int pktSize = (pktSizeBytes[0] & 0xff) | ((pktSizeBytes[1] & 0xff) << 8);
		byte[] rawBytes = new byte[pktSize];
		txtConverter.decode(decodeStringBytes, bytesRead, decodeStringBytes.length - bytesRead, pktSize, rawBytes);
		
		if (0 != (rawBytes[Packet.OFFSET_FLAGS] & Packet.FLAG_SPECIAL)) {
			switch (rawBytes[Packet.FIXED_HEADER_SIZE + SpecialServerPacket.OFFSET_SPECIAL_TYPE]) {
			case SpecialServerPacket.SPECIAL_TYPE_CONNECTION_ACCEPTED:
				return new ConnectionAcceptedServerPacket(rawBytes);
			case SpecialServerPacket.SPECIAL_TYPE_CONNECTION_CLOSED:
				return new ConnectionClosedServerPacket(rawBytes);
			default:
				throw new ProtocolException("Bad special type on special packet.");
			}
		}
		return new ServerPacket(rawBytes);
	}
	
}
