package org.bench4q.web.masterMessager;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
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.springframework.stereotype.Component;

@Component
public class AgentManagerMessager extends MasterMessager {

	public AgentManagerMessager() {
		super(MasterAddressManamger.getMasterAddress() + "/agentManage");
	}

	public AgentResponseModel addAgent(String accessToken,
			String agentModelContent) {
		System.out.println("enter and agent");
		String url = this.getBaseUrl() + "/addAgentToPool";
		HttpResponse httpResponse = null;
		try {
			httpResponse = this.getHttpRequester().sendPostXml(url,
					agentModelContent, makeAccessTockenMap(accessToken));
			System.out.println("agent:"+httpResponse.getContent());
			if (!validateHttpResponse(httpResponse)) {
				handleInvalidatedResponse(url);
				createFaliAgentResponseModel();
			}

			return (AgentResponseModel) MarshalHelper.unmarshal(
					AgentResponseModel.class, httpResponse.getContent());
		} catch (Exception e) {
			this.handleException(httpResponse, e);
			return createFaliAgentResponseModel();

		}

	}

	public AgentResponseModel deleteAgent(String accessToken, String agentId,
			String hostName) {
		String url = this.getBaseUrl() + "/removeAgentFromPool";
		Map<String, String> params = new HashMap<String, String>();
		params.put("agentId", agentId);
		params.put("hostName", hostName);
		return this.getAgentResponseModel(url, params, accessToken);
	}

	public AgentResponseModel loadAgents(String accessToken) {
		String url = this.getBaseUrl() + "/queryAgentList";
		AgentResponseModel agentResponseModel = this.getAgentResponseModel(url,
				null, accessToken);
		if (agentResponseModel.getAgents() == null) {
			agentResponseModel.setAgents(new LinkedList<AgentModel>());
		}
		return agentResponseModel;
	}

	private AgentResponseModel getAgentResponseModel(String url,
			Map<String, String> params, String accessToken) {

		HttpResponse httpResponse = null;
		try {
			httpResponse = this.getHttpRequester().sendGet(url, params,
					makeAccessTockenMap(accessToken));
			if (!validateHttpResponse(httpResponse)) {
				handleInvalidatedResponse(url);
				return createFaliAgentResponseModel();
			}

			return (AgentResponseModel) MarshalHelper.unmarshal(
					AgentResponseModel.class, httpResponse.getContent());
		} catch (Exception e) {
			this.handleException(httpResponse, e);
			return createFaliAgentResponseModel();

		}
	}

	private AgentResponseModel createFaliAgentResponseModel() {
		AgentResponseModel agentResponseModel = new AgentResponseModel();
		agentResponseModel.setSuccess(false);
		agentResponseModel.setFailCauseString(this.SERVER_ERROR);
		return agentResponseModel;
	}

}
