package generating;

import logging.Logger;
import mapping.Mapper;

/**
 * 
 * @author Majd Kokaly
 * 
 * The GeneratorsController is responsible for generating a Job Generator Thread for
 * every JobClass in the system.
 * 
 */
public class GeneratorsController {
	
	/**
	 * The Mapper object to send jobs for. 
	 */
	private Mapper mapper;
	
	/**
	 * An array of JobsGenerator objects
	 */
	private JobsGenerator[] generators;
	
	/**
	 * An array of threads. There is a thread for every generator 
	 * @see GeneratorsController#generators
	 */
	private Thread threads[];
	
	/**
	 * 
	 * @param mapper Object that the data member mapper is set to
	 */
	public GeneratorsController(Mapper mapper) {
		this.setMapper(mapper);
	}

	/**
	 * This creates a Thread for every Job Generator and starts them
	 */
	public void startGenerators() 
	{
		this.setGenerators(new JobsGenerator[this.getMapper().getClassesTable().size()]);
		this.setThreads(new Thread[getMapper().getClassesTable().size()]);
		this.logTheStartDate();
		
		for (int i = 0; i < this.getMapper().getClassesTable().size(); i++) 
		{
			this.getGenerators()[i] = new JobsGenerator(this.getMapper().getClassesTable().get(i + 1), this.getMapper());
			this.getThreads()[i] = new Thread(this.getGenerators()[i]);
			this.getThreads()[i].start();
		}
		
	}
	
	/**
	 * This method logs the start date of the generation process
	 */
	public void logTheStartDate() 
	{
		Logger logger = new Logger("generating");
		logger.log("");
		logger.closeStreams();

	}
	
	/**
	 * This method stops the threads
	 */
	public void stopGenerators() 
	{
		for (int i = 0; i < this.getGenerators().length; i++) {
			this.getGenerators()[i].setAlive(false);
			this.getThreads()[i].interrupt();
			this.getThreads()[i] = null;
		}
	}

	public Mapper getMapper() {
		return mapper;
	}

	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}

	public JobsGenerator[] getGenerators() {
		return generators;
	}

	public void setGenerators(JobsGenerator[] generators) {
		this.generators = generators;
	}

	public Thread[] getThreads() {
		return threads;
	}

	public void setThreads(Thread[] threads) {
		this.threads = threads;
	}

}
