package at.ac.tuwien.lsdc.sched;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.lsdc.exception.OutOfPMsException;
import at.ac.tuwien.lsdc.types.Application;
import at.ac.tuwien.lsdc.types.PhysicalMachine;
import at.ac.tuwien.lsdc.types.ScenarioType;
import at.ac.tuwien.lsdc.types.SchedulerEvent;
import at.ac.tuwien.lsdc.types.SchedulerType;
import at.ac.tuwien.lsdc.types.VirtualMachine;
import at.ac.tuwien.lsdc.types.VirtualMachine.VMType;

public class SchedulerC extends AbstractSchedulerWithMigration {

	private static final Logger LOG = LoggerFactory.getLogger(SchedulerC.class);

	public SchedulerC(int numPMs, int numCloudPartners, File schedulerLog, ScenarioType scenario)
			throws IOException {
		super(numPMs, numCloudPartners, schedulerLog, scenario);

		this.vmType = VMType.NonResizable;
	}

	@Override
	protected boolean deployApp(VirtualMachine vm, Application app) {
		boolean deployed = false;
		if (!vm.enoughResources(app))
			return false;

		deployed = vm.startApplication(app);
		if (deployed)
			app.setRunningOn(vm);
		return deployed;
	}

	/**
	 * Cleanup completed apps. If an VM becomes empty, shut down VM + PM.
	 *
	 * @param events list of all events that happened in this timeslot.
	 */
	@Override
	protected void handleEndEvents(LinkedList<SchedulerEvent> events) {
//		LOG.debug("stopApps():" + events);
		for (SchedulerEvent evt : events) {
			VirtualMachine vm = evt.getApp().getRunningOn();
			evt.getApp().setRunningOn(null);
			vm.stopApplication(evt.getApp());

			numStopped++;

			if (vm.getApplications().size() == 0) {
				PhysicalMachine pm = vm.getRunningOn();
				pm.stopVirtualMachine(vm);
				manager.stopPhysicalMachine(pm.getId());
			}
		}
	}


	/**
	 * Try to start all Apps. If not enough space start another PM, if not possible,
	 * delay start.
	 *
	 * @param events list of all events that happened in this timeslot.
	 */
	@Override
	protected void handleStartEvents(LinkedList<SchedulerEvent> events) {
//		LOG.debug("startApps():" + events);
		boolean deployed = false;
		for (SchedulerEvent evt : events) {
			deployed = false;
			VirtualMachine vm = null;
			List<PhysicalMachine> sortedPMs = manager.getRevSortedPMs();

			for (PhysicalMachine pm : sortedPMs) {
				if (pm.isRunning() && (pm.countCurrentlyRunningVMs() > 0)) {
					vm = pm.getVirtualMachines().values().iterator().next();
					deployed = deployApp(vm, evt.getApp());
					if (deployed)
						break;
				}
			}
			if (!deployed) {
				try {
					vm = manager.startPhysicalMachine().startVirtualMachine(vmType);
					deployed = deployApp(vm, evt.getApp());
				} catch (OutOfPMsException e) {
					if (federation.askToOutsource(evt.getApp())) {
						insertOutsourcedStartEvent(currTime + 1, evt.getApp());
					} else {
//						LOG.info("delaying the start of:" + evt.getApp());
						delayedApps.add(evt.getApp());
					}
				}
			}
			if (deployed) {
				insertStopEvent(currTime + evt.getApp().getDuration(), evt.getApp());

				numStarted++;

				if(manager.countCurrentlyRunningPMs() < manager.getMaxPMs()) {
					Application app = federation.askToInsource();
					if(app != null) {
						insertInsourcedStartEvent(currTime + 1, evt.getApp());
					}
				}
			}
		}
	}

	@Override
	protected String getSchedulerType() {
		return SchedulerType.C.toString();
	}

}
