package eu.dnetlib.xml.database.exist;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class creates a temporary exist database instances.
 *
 * @author marko
 *
 */
public class TemporaryExistDatabase extends ExistDatabase {
	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(TemporaryExistDatabase.class); // NOPMD by marko on 11/24/08 5:02 PM

	/**
	 * temporary directory. this way we won't delete other things on shutdown if somebody changes the configuration file
	 * location with setConfigFile().
	 */
	private transient File tempDirectory;

	/**
	 * this config file will be copied to a newly created temporary directory.
	 */
	private String configTemplate = "default-exist-conf.xml";

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.xml.database.exist.ExistDatabase#start()
	 */
	@Override
	public void start() {
		log.warn("STARTING TEMPORARY EXIST DATABASE");
		createTemporaryDatabase();
		super.start();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.xml.database.exist.ExistDatabase#stop()
	 */
	@Override
	public void stop() {
		super.stop();
		try {
			FileUtils.deleteDirectory(tempDirectory);
		} catch (IOException e) {
			log.fatal("cannot delete temporary exist directory", e);
		}
	}

	/**
	 * create a temporary directory and copy the default configuration file.
	 */
	protected void createTemporaryDatabase() {
		log.debug("creating temp database");
		try {
			File tmpName;
			tmpName = File.createTempFile("exist", "");

			tmpName.delete();

			tempDirectory = new File(tmpName.getAbsolutePath());
			new File(tempDirectory, "data").mkdirs();

			final InputStream defaultConf = getClass().getResourceAsStream(getConfigTemplate());
			if (defaultConf == null)
				throw new IOException("cannot find " + getConfigTemplate());

			final File existConfigFile = new File(tempDirectory, "conf.xml");
			final FileOutputStream confOutput = new FileOutputStream(existConfigFile);

			try {
				IOUtils.copy(defaultConf, confOutput);
			} finally {
				confOutput.close();
			}

			setConfigFile(existConfigFile.getAbsolutePath());
		} catch (IOException e) {
			log.fatal("creating database dir", e);
			throw new IllegalStateException(e);
		}
		log.debug("created temp database");
	}

	protected String getConfigTemplate() {
		return configTemplate;
	}

	protected void setConfigTemplate(final String configTemplate) {
		this.configTemplate = configTemplate;
	}

}
