package org.bench4q.master.unitTest.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AgentModel;
import org.bench4q.share.models.master.AgentResponseModel;
import org.junit.Before;
import org.junit.Test;

public class AgentPoolControllerTest extends TestBase {
	private final String URLSTRING = BASE_URL + "/agentManage";
	private final static String HOSTNAME1 = "127.0.0.1";
	private final static String HOSTNAME2 = "133.133.12.9";

	@Before
	public void prepare() {
		this.setAccessTocken(this.login());
	}

	@Test
	public void testAdd() throws JAXBException, IOException {
		this.setAccessTocken(this.login());
		this.addAgentToPool(HOSTNAME2);
		// test.removeAgentToPool();
		this.loadAgentsFromPool();
	}

	public void addAgentToPool(String hostName) throws JAXBException,
			IOException {
		String urlString = this.URLSTRING + "/addAgentToPool";
		AgentResponseModel agentResponseModel = new AgentResponseModel();

		AgentModel agent = new AgentModel();
		agent.setHostName(hostName);
		agent.setMaxLoad(500);
		agent.setRemainLoad(500);
		agent.setPort(6565);
		System.out.println(urlString);
		System.out.println(MarshalHelper.marshal(AgentModel.class, agent));
		HttpResponse httpResponse = this.httpRequester.sendPostXml(urlString,
				MarshalHelper.marshal(AgentModel.class, agent),
				makeAccessTockenMap(this.getAccessTocken()));

		agentResponseModel = (AgentResponseModel) MarshalHelper.unmarshal(
				AgentResponseModel.class, httpResponse.getContent());

		System.out.println(httpResponse.getContent());
		System.out.println(agentResponseModel.isSuccess());
	}

	public void removeAgentToPool() throws IOException, JAXBException {
		Map<String, String> propertiesMap = new HashMap<String, String>();
		propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
				+ this.accessTocken);

		String urlString = this.URLSTRING + "/removeAgentFromPool";
		Map<String, String> map = new HashMap<String, String>();
		map.put("hostName", HOSTNAME1);
		HttpResponse httpResponse = this.httpRequester.sendGet(urlString, map,
				propertiesMap);
		System.out.println(httpResponse.getContent());
	}

	public void loadAgentsFromPool() throws IOException {
		Map<String, String> propertiesMap = new HashMap<String, String>();
		propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
				+ this.accessTocken);

		String urlString = this.URLSTRING + "/queryAgentList";
		HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
				null, propertiesMap);
		System.out.println(httpResponse.getContent());
	}

}
