package scheduler;

import java.util.Map;
import java.util.TimerTask;
import java.util.logging.Logger;

import common.Direction;
import common.LoggerUtil;
import communication.messages.ElevatorMoveMessage;

/**
 * Task that runs when elevator gets stuck
 */
public class ElevatorTimerTask extends TimerTask {

	private static final Logger logger = LoggerUtil.getLoggerForClass(ElevatorTimerTask.class);
	private MetaElevator elevator;

	public ElevatorTimerTask(MetaElevator metaElevator) {
		this.elevator = metaElevator;
	}

	@Override
	public void run() {
		SystemGUI systemGUI = SystemGUI.getInstance();
		systemGUI.updateElevatorLocationAfterError(elevator.getElevatorId(), elevator.getCurrentFloor());
		systemGUI.updateElevatorStatus(elevator.getElevatorId(), "ELEVATOR STUCK");
		
		Map<Integer, Direction> destinations = elevator.getDestinationsForReroute();
		Scheduler scheduler = Scheduler.getInstance();

		// remove the elevator so re-routed destinations dont get assigned to this elevator
		scheduler.removeElevator(elevator);

		MetaElevator idleMetaElevator = scheduler.getIdleElevator();
		destinations.forEach((floor, direction) -> {
			logger.info("Rerouting request from floor " + floor + ". Queuing elevator " + idleMetaElevator.getElevatorId());
			scheduler.addTask(new ElevatorDispatchTask(new ElevatorMoveMessage(floor, idleMetaElevator.getElevatorId()), direction));
		});
	}
}
