package org.bench4q.master.unitTest.transaction;

import static org.junit.Assert.*;

import java.util.List;
import java.util.UUID;

import org.bench4q.master.domain.RunningAgentInterface;
import org.bench4q.master.domain.entity.Agent;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.factory.RunningAgentFactory;
import org.bench4q.master.domain.valueobject.transaction.impl.ScriptLoadApplication;
import org.bench4q.master.unitTest.TestBase_MakeUpTestPlan;
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:mockHttpMesseger-context.xml" })
public class Test_ScriptLoadCommand extends TestBase_MakeUpTestPlan {
	private static final String Test_AGENT_HOSTNAME = "127.0.0.1";
	private UUID agentRunId;

	@Autowired
	private RunningAgentFactory runningAgentFactory;

	private UUID getAgentRunId() {
		return agentRunId;
	}

	private void setAgentRunId(UUID agentRunId) {
		this.agentRunId = agentRunId;
	}

	@Before
	public void prepare() {
		this.getAgentService().addAgentToPool(
				Agent.createAgentWithoutId("127.0.0.1", 6565, 500));
	}

	@After
	public void cleanUp() {
		Agent agent = this.getAgentRepository().getAgentBy(Test_AGENT_HOSTNAME);
		this.getAgentMessenger().stop(agent, this.getAgentRunId());
		this.getAgentRepository().detach(agent.getId());
	}

	@Test
	public void testExecuteWithTestPlanScript() {
		submitATestPlanWithOneScript();
		this.getHaPool().checkAllHeartBeat();
		TestPlanScript testPlanScript = this.getTestPlanRepository()
				.getTestPlanInDomainBy(getTestPlanRunIdUuid())
				.extracSpecifiedScript(this.getScriptId());
		ScriptLoadApplication scriptLoadCommand = new ScriptLoadApplication(
				testPlanScript, testPlanScript.getRequireLoad(),
				this.getHaPool());
		List<? extends RunningAgentInterface> runningAgents = null;
		synchronized (this.getHaPool()) {
			runningAgents = scriptLoadCommand.execute();
		}

		assertNotNull(runningAgents);
		assertNotNull(runningAgents.get(0));
		assertNotNull(runningAgents.get(0).getAgentRunId());
		this.setAgentRunId(runningAgents.get(0).getAgentRunId());
		assertEquals(EACH_SCRIPT_LOAD_SMALLSCALE, runningAgents.get(0)
				.getLoadInUse());
	}
}
