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 MySqlUserProcessorFactory implements EntityProcessorFactory {

	public <T extends AbstractEntity> Processor createCreateProcessor(EntityManager em, T entity) {
		DatabaseUser dbu = (DatabaseUser) entity;
		assert dbu.getInstance().equals("mysql");
		JDBCProcessor aJDBCP = MySqlDatabaseProcessorFactory.createMySqlAdminProcessor();
		String aName = AbstractEntity.escapeString(dbu.getName());
		String aPassword = AbstractEntity.escapeString(dbu.getPassword());
		aJDBCP.addSQL("CREATE USER '" + aName + "'@'%'" + " IDENTIFIED BY '" + aPassword + "'");
		return aJDBCP;
	}

	public <T extends AbstractEntity> Processor createUpdateProcessor(
			EntityManager em, T entity) {
		DatabaseUser dbu = (DatabaseUser) entity;
		assert dbu.getInstance().equals("mysql");
		JDBCProcessor aJDBCP = MySqlDatabaseProcessorFactory.createMySqlAdminProcessor();
		String aName = AbstractEntity.escapeString(dbu.getName());
		String aPassword = AbstractEntity.escapeString(dbu.getPassword());
		aJDBCP.addSQL("SET PASSWORD FOR  '" + aName + "'@'%'" + " = PASSWORD('" + aPassword + "')");
		return aJDBCP;
	}

	public <T extends AbstractEntity> Processor createDeleteProcessor(
			EntityManager em, T entity) {
		DatabaseUser dbu = (DatabaseUser) entity;
		assert dbu.getInstance().equals("mysql");

		JDBCProcessor aJDBCP = MySqlDatabaseProcessorFactory.createMySqlAdminProcessor();
		String aName = AbstractEntity.escapeString(dbu.getName());
		aJDBCP.addSQL("REVOKE ALL PRIVILEGES, GRANT OPTION FROM '" + aName + "'@'%'");
		aJDBCP.addSQL("DROP USER '" + aName + "'@'%'");
		return aJDBCP;
	}
}
