package de.hsadmin.remote;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Map;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DatabaseCleanTest {

	private static final String MODULE_MYSQL_DB = "mysqldb";
	private static final String MODULE_PGSQL_DB = "postgresqldb";
	private static final String MODULE_MYSQL_USER = "mysqluser";
	private static final String MODULE_PGSQL_USER = "postgresqluser";
	
	private XmlRpcClient client;
	private RemoteCASHelper cas;

	@Before
	public void setUp() throws Exception {
		client = RemoteTestHelper.getClient();
		cas = new RemoteCASHelper();
	}

	@After
	public void tearDown() throws Exception {
		client = null;
		cas = null;
	}

	@Test
	public void testDelete() {
		delete(MODULE_MYSQL_DB, "aaa00_db1");
		delete(MODULE_PGSQL_DB, "aaa00_db2");
		delete(MODULE_MYSQL_USER, "aaa00_dba");
		delete(MODULE_PGSQL_USER, "aaa00_dba");
	}

	private void delete(String module, String name) {
		int count = getDBsCount(module);
		String user = "aaa00";
		String grantingTicketURL = cas.getGrantingTicketURL(user);
		Map<String, String> whereParams = new HashMap<String, String>();
		whereParams.put("name", name);
		Object[] params = new Object[] { user, 
				cas.getServiceTicket(grantingTicketURL, RemoteTestHelper.getBackendURL()), 
				whereParams };
		try {
			Object execute = client.execute(module + ".delete", params);
			assertNull(execute);
		} catch (XmlRpcException e) {
			fail(e.getMessage());
		}
		assertEquals(count - 1, getDBsCount(module));
	}

	private int getDBsCount(String module) {
		int count = 0;
		String user = "aaa00";
		String grantingTicketURL = cas.getGrantingTicketURL(user);
		Map<String, String> whereParams = new HashMap<String, String>();
		Object[] params = new Object[] { user, 
				cas.getServiceTicket(grantingTicketURL, RemoteTestHelper.getBackendURL()), 
				whereParams };
		try {
			Object execute = client.execute(module + ".search", params);
			Object[] result = (Object[]) execute;
			count = result.length;
		} catch (XmlRpcException e) {
			fail(e.getMessage());
		}
		return count;
	}

}
