package de.vfst.odb;

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

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ODBSetup
{
	private static final String CONFIGFILE = "objectdb.conf";

	public EntityManagerFactory setUpDB(String dbName, File basePath)
	{
		File database = new File(basePath, dbName + ".objectdb");
		if (database.exists())
		{
			database.delete();
		}
		System.setProperty("objectdb.home", database.getParentFile().getAbsolutePath());
		File config = new File(basePath, CONFIGFILE);
		if (!config.exists())
		{
			createDBConfig(config);
		}
		return Persistence.createEntityManagerFactory(database.getAbsolutePath());
	}

	private void createDBConfig(File configFile)
	{
		if (!configFile.exists())
		{
			File dir = configFile.getParentFile();
			if (!dir.exists() && !dir.mkdirs())
			{
				throw new IllegalStateException("Could not create base directory for ObjectDB " + dir.getAbsolutePath());
			}
			try
			{
				configFile.createNewFile();
			}
			catch (IOException e)
			{
				throw new IllegalStateException("Unable to create configuration file: " + e.getMessage());
			}
		}
		try (InputStream input = this.getClass().getClassLoader().getResourceAsStream("META-INF/" + CONFIGFILE);
				FileOutputStream output = new FileOutputStream(configFile);)
		{
			byte[] buffer = new byte[1024];
			int count;
			do
			{
				count = input.read(buffer);
				if (count > 0)
				{
					output.write(buffer, 0, count);
				}
			}
			while (count > 0);
		}
		catch (IOException iox)
		{
			throw new IllegalStateException("Could not set up configuration for TestDB (ObjectDB) due to "
					+ iox.getClass().getSimpleName() + ": " + iox.getMessage());
		}
	}

}