package org.bench4q.web.masterMessager;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
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.OrganizeRecordPortResponseModel;
import org.bench4q.share.models.master.PortModel;
import org.springframework.stereotype.Component;

@Component
public class RecordPortMessager extends MasterMessager {

	public RecordPortMessager() {
		super(MasterAddressManamger.getMasterAddress() + "/RecordPort");
	}

	public OrganizeRecordPortResponseModel addPort(String accessToken,
			String port) {
		String url = this.getBaseUrl() + "/addPortToPortPool";
		Map<String, String> params = new HashMap<String, String>();
		params.put("port", port);
		return getOrganizeRecordPortResponseModel(url, params, accessToken);

	}

	public OrganizeRecordPortResponseModel deletePort(String accessToken,
			String port) {
		String url = this.getBaseUrl() + "/removePortFromPool";
		Map<String, String> params = new HashMap<String, String>();
		params.put("portId", port);
		return getOrganizeRecordPortResponseModel(url, params, accessToken);
	}

	public OrganizeRecordPortResponseModel loadPorts(String accessToken) {
		String url = this.getBaseUrl() + "/loadPortList";
		return getOrganizeRecordPortResponseModel(url, null, accessToken);
	}

	private OrganizeRecordPortResponseModel getOrganizeRecordPortResponseModel(
			String url, Map<String, String> params, String accessToken) {
		HttpResponse httpResponse = null;
		try {

			httpResponse = this.getHttpRequester().sendPost(url, params,
					makeAccessTockenMap(accessToken));
			if (!validateHttpResponse(httpResponse))
				return null;
			return extractOrganizeRecordPortResponseModel(httpResponse);
		} catch (Exception e) {
			this.handleException(httpResponse, e);
			return createFailOrganizeRecordPortResponseModel();
		}

	}

	private OrganizeRecordPortResponseModel createFailOrganizeRecordPortResponseModel() {
		OrganizeRecordPortResponseModel organizeRecordPortResponseModel = new OrganizeRecordPortResponseModel();
		organizeRecordPortResponseModel.setSuccess(false);
		organizeRecordPortResponseModel.setFailCauseString("");
		return organizeRecordPortResponseModel;
	}

	private OrganizeRecordPortResponseModel extractOrganizeRecordPortResponseModel(
			HttpResponse httpResponse) throws JAXBException {
		OrganizeRecordPortResponseModel organizeRecordPortResponseModel = (OrganizeRecordPortResponseModel) MarshalHelper
				.unmarshal(OrganizeRecordPortResponseModel.class,
						httpResponse.getContent());
		if (organizeRecordPortResponseModel.getPortModels() == null) {
			List<PortModel> ports = new LinkedList<PortModel>();
			organizeRecordPortResponseModel.setPortModels(ports);

		}
		return organizeRecordPortResponseModel;
	}
}
