package de.hsadmin.mods.db;

import javax.persistence.EntityManager;

import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.qserv.EntityProcessorFactory;
import de.hsadmin.core.qserv.Processor;

/**
 * Factory class which creates Processor instances for dealing with UNIX user
 * accounts.
 * 
 * @author mi
 */
public class PgSqlDatabaseProcessorFactory implements EntityProcessorFactory {
	/**
	 * creates a JDBCProcessor for PostgreSQL and the given user
	 * 
	 * @param user
	 * @param password
	 * @return
	 */
	public static JDBCProcessor createPostgreSqlProcessor(String user, String password) {
		return new JDBCProcessor("org.postgresql.Driver",
				"jdbc:postgresql://localhost/template1", user, password);
	}

	/**
	 * creates a JDBCProcessor for the PostgreSQL admin user
	 * 
	 * @return
	 */
	public static JDBCProcessor createPostgreSqlAdminProcessor() {
		return new JDBCProcessor("org.postgresql.Driver", "jdbc:postgresql://localhost/template1");
	}

	/**
	 * @return a Processor which creates a new database
	 */
	public <T extends AbstractEntity> Processor createCreateProcessor(EntityManager em, T entity) {
		Database db = (Database) entity;
		assert db.getInstance().equals("pgsql");
		JDBCProcessor aJDBCP = null;
		String aName = AbstractEntity.escapeString(db.getName());
		String aOwner = AbstractEntity.escapeString(db.getOwner());
		String aEncoding = AbstractEntity.escapeString(db.getEncoding());
		aJDBCP = createPostgreSqlAdminProcessor();
		aJDBCP.addSQL("CREATE DATABASE " + aName + " OWNER=" + aOwner + " ENCODING='" + aEncoding + "' TEMPLATE template0");
		return aJDBCP;
	}

	/**
	 * @return a Processor which updates a preexisting database
	 */
	public <T extends AbstractEntity> Processor createUpdateProcessor(EntityManager em, T entity) {
		Database db = (Database) entity;
		assert db.getInstance().equals("pgsql");
		String aName = AbstractEntity.escapeString(db.getName());
		String aOwner = AbstractEntity.escapeString(db.getOwner());
		JDBCProcessor aJDBCP = null;
		aJDBCP = createPostgreSqlAdminProcessor();
		aJDBCP.addSQL("ALTER DATABASE " + aName + " OWNER TO " + aOwner);
		return aJDBCP;
	}

	/**
	 * @return a Processor which deletes an existing database
	 */
	public <T extends AbstractEntity> Processor createDeleteProcessor(EntityManager em, T entity) {
		Database db = (Database) entity;
		assert db.getInstance().equals("pgsql");
		JDBCProcessor aJDBCP = createPostgreSqlAdminProcessor();
		String aName = AbstractEntity.escapeString(db.getName());
		aJDBCP.addSQL("DROP DATABASE " + aName);
		return aJDBCP;
	}
}
