package elevator;

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

import common.ErrorType;
import common.LoggerUtil;
import communication.MessageSender;
import communication.Port;
import communication.messages.ElevatorSensorMessage;
import error.ExceptionUtil;
import error.UnknownAddressException;

/**
 * A class to represent all of the arrival sensors on all the elevators
 */
public class ElevatorSensor {
	private static final Logger logger = LoggerUtil.getLoggerForClass(ElevatorSensor.class);
	private long floorMoveTimeMs;
	private MessageSender messageSender;

	/**
	 * Construct a new elevator sensor object
	 *
	 * @param messageSender
	 */
	public ElevatorSensor(MessageSender messageSender) {
		this.messageSender = messageSender;
	}

	public void setFloorMoveTimeMs(long time) {
		this.floorMoveTimeMs = time;
	}

	/**
	 * Initiates the movement simulation procedure for a particular elevator to move
	 * one floor
	 *
	 * @param elevator
	 * @param destFloor
	 */
	public void handleMovementStarted(Elevator elevator, int destFloor) {
		new Thread(() -> {
			try {
				Thread.sleep(floorMoveTimeMs);
			} catch (InterruptedException e) {
				ExceptionUtil.handleRecoverableException(e, "Interrupt occured while waiting", logger);
				Thread.currentThread().interrupt();
			}

			int elevatorId = elevator.getElevatorId();
			ErrorType errorType = elevator.getErrorForFloor(destFloor);

			if (errorType == ErrorType.STUCK_MOTOR) {
				logger.severe("Error occured in elevator" + elevatorId + " while trying to move to floor " + destFloor
						+ ": Error: " + errorType);
			} else {
				try {
					logger.fine("Simulating an elevator sensor movement event at floor " + destFloor + " for elevator "
							+ elevatorId);
					messageSender.sendMessage(new ElevatorSensorMessage(destFloor, elevatorId), Port.SCHEDULER);
				} catch (IOException | UnknownAddressException e) {
					ExceptionUtil.handleRecoverableException(e, "Could not report elevator position to scheduler",
							logger);
				}
			}
		}).start();
	}
}
