package elevator;

import java.io.IOException;
import java.util.logging.Logger;

import common.AbstractReceiver;
import common.LoggerUtil;
import communication.MessageUtil;
import communication.Port;
import communication.messages.ElevatorActionMessage;
import communication.messages.InitializeMessage;
import communication.messages.Message;
import error.ExceptionUtil;
import error.UnexpectedMessageTypeException;

/**
 * This class receives message from scheduler
 */
public class ElevatorReceiver extends AbstractReceiver {
	private static final Logger logger = LoggerUtil.getLoggerForClass(ElevatorReceiver.class);
	private final ElevatorSubsystem elevatorSubsystem;

	public ElevatorReceiver() throws IOException {
		super(Port.ELEVATOR);
		elevatorSubsystem = new ElevatorSubsystem();
	}

	@Override
	public void handleMessage(Message msg) throws IOException {
		if (msg instanceof InitializeMessage) {
			logger.config("Received initialize message from Scheduler");
			elevatorSubsystem.initializeSystem((InitializeMessage) msg);
		} else if (msg instanceof ElevatorActionMessage) {
			elevatorSubsystem.handleMessage((ElevatorActionMessage) msg);
		} else {
			ExceptionUtil.handleRecoverableException(new UnexpectedMessageTypeException(),
					"Received a message not meant for this subsystem", logger);
		}
	}

	public static void main(String[] args) {
		MessageUtil.setIPAddress(Port.SCHEDULER, args, 0);

		try {
			new ElevatorReceiver().receiveAndHandlePackets(logger);
		} catch (IOException e) {
			ExceptionUtil.handleCriticalException(e, "An IO Exception occured while operating elevator receiver",
					logger);
		}
	}
}
