package org.bench4q.master.unitTest.service;

import static org.junit.Assert.*;

import org.bench4q.master.domain.entity.Agent;
import org.bench4q.master.domain.repository.AgentRepository;
import org.bench4q.master.domain.service.AgentService;
import org.bench4q.master.infrastructure.highavailable.HighAvailablePool;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_AgentService {
	private static final String hostNameForTest = "133.133.12.5";
	private AgentService agentService;
	private AgentRepository agentRepoitory;
	private HighAvailablePool highAvailablePool;

	private AgentService getAgentService() {
		return agentService;
	}

	@Autowired
	private void setAgentService(AgentService agentService) {
		this.agentService = agentService;
	}

	private AgentRepository getAgentRepoitory() {
		return agentRepoitory;
	}

	@Autowired
	private void setAgentRepoitory(AgentRepository agentRepoitory) {
		this.agentRepoitory = agentRepoitory;
	}

	private HighAvailablePool getHighAvailablePool() {
		return highAvailablePool;
	}

	@Autowired
	private void setHighAvailablePool(HighAvailablePool highAvailablePool) {
		this.highAvailablePool = highAvailablePool;
	}

	@Test
	public void testAddAgentToPool() {
		Agent agent = getAgentForTest();
		assertNotNull(this.getHighAvailablePool().getPool()
				.get(hostNameForTest));
		assertNotNull(agent);
	}

	private Agent getAgentForTest() {
		return this.getAgentRepoitory().getAgentBy(hostNameForTest);
	}

	private boolean doAddAgent() {
		return this.getAgentService().addAgentToPool(
				Agent.createAgentWithoutId(hostNameForTest, 6565, 500));
	}

	@Before
	public void prepare() {
		doAddAgent();
	}

	@After
	public void cleanUp() {
		this.getAgentService().removeAgentFromPool(getAgentForTest().getId());
	}

	@Test
	public void tsetRemoveAgentFromPool() {
		Agent agent = getAgentForTest();
		assertTrue(agent != null);
		assertTrue(this.getAgentService().removeAgentFromPool(agent.getId()));
		assertNull(getAgentForTest());
		doAddAgent();
	}

	@Test
	public void testLoadAgentPoolFromDB() {
		this.getAgentService().removeAgentFromPool(getAgentForTest().getId());
		int sizeBeforeAdd = this.getAgentService().loadAgentPoolFromDB().size();
		doAddAgent();
		int sizeAfterAdd = this.getAgentService().loadAgentPoolFromDB().size();
		assertEquals(sizeBeforeAdd + 1, sizeAfterAdd);
	}

}
