package communication;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

import communication.messages.Message;
import error.ExceptionUtil;

/**
 * Utility functions for messages
 */
public class MessageUtil {
	public static final int BUFFER_SIZE = 1000;

	private MessageUtil() {
		throw new UnsupportedOperationException("Utility class");
	}

	/**
	 * Convert a byte array into the corresponding message class type
	 *
	 * @param data the byte array to convert
	 * @return the converted message
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Message byteArrayToMessage(byte[] data) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		ObjectInputStream ois = new ObjectInputStream(bais);
		return Message.class.cast(ois.readObject());
	}

	/**
	 * Sets a ip address to a
	 * @param port
	 * @param InetAddress
	 * @param messageSender
	 */
	public static void setIPAddress(Port port, String[] args, int index) {
		boolean isLocalHost = args == null || args.length == 0 || args[index] == null || args[index].isEmpty();
		try {
			MessageSender.setAddress(port, isLocalHost ? InetAddress.getLocalHost() : InetAddress.getByName(args[index]));
		} catch (UnknownHostException e) {
			ExceptionUtil.handleCriticalException(e, "Unknown IP address");
		}
	}
}
