package de.hottis.MeasurementCollector;

import java.util.List;
import java.util.Properties;
import java.util.Timer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class DatabaseEngine extends Thread implements ITriggerable {
	final protected Logger logger = LogManager.getRootLogger();

	private Properties config;
	private DataObjectQueue queue;
	private boolean stop;
	private boolean triggerFlag;
	private Timer timer;

	public DatabaseEngine(Properties config, DataObjectQueue queue) {
		super("MeasurementCollector.DatabaseEngine");
		this.config = config;
		this.queue = queue;
		this.stop = false;
		this.triggerFlag = false;
	}

	public void requestShutdown() {
		logger.info("Shutdown of database engine requested");
		this.stop = true;
		try {
			this.join();
			logger.info("Database engine is down");
		} catch (InterruptedException e) {
			logger.error("Waiting for shutdown of database engine interrupted"); 
		}
	}
	
	public synchronized void trigger() {
		logger.debug("DatabaseEngine triggered");
		triggerFlag = true;
		notify();
	}
	
	public void init() {
		timer = new Timer("DatabaseEngineTrigger");
		timer.schedule(new TriggerTimer(this), 0, 60 * 1000);
	}
	
	@Override
	public synchronized void run() {
		while (! stop) {
			logger.debug("DatabaseEngine is about to wait");
			while (! triggerFlag) {
				try {
					wait();
				} catch (InterruptedException e) {
				}
			}
			triggerFlag = false;
			logger.debug("DatabaseEngine has received trigger");

			try {
				while (true) {
					List<ADataObject> adol = queue.peek();
					if (adol == null) {
						break;
					}
					
					for (ADataObject ado : adol) {
						logger.debug(ado);
					}

					queue.remove(adol);
				}				
			} catch (Exception e) {
				logger.error("Exception in outer database engine loop", e);
			}
		}
	}
}
