package org.bench4q.web.masterMessager;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.ExceptionLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public abstract class MasterMessager {
	private final String AUTH_HEADER_PROPERTY = "Authorization";
	private final String ACCES_TOCKEN_STARTER = "Bearer ";
	protected final String SERVER_ERROR = "web server error";
	protected String baseUrl;
	protected HttpRequester httpRequester;
	protected Logger logger = Logger.getLogger(MasterMessager.class);

	public String getBaseUrl() {
		return baseUrl;
	}

	protected void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	protected HttpRequester getHttpRequester() {
		return httpRequester;
	}

	@Autowired
	private void setHttpRequester(HttpRequester httpRequester) {
		this.httpRequester = httpRequester;
	}

	public MasterMessager(String baseUrl) {
		this.setBaseUrl(baseUrl);
	}

	protected Map<String, String> makeAccessTockenMap(String accessToken) {
		Map<String, String> properties = new HashMap<String, String>();
		properties
				.put(AUTH_HEADER_PROPERTY, ACCES_TOCKEN_STARTER + accessToken);
		return properties;
	}

	protected void handleException(HttpResponse httpResponse, Exception e) {
		if (httpResponse != null)
			logger.error(httpResponse.getContent());
		logger.error(ExceptionLog.getStackTrace(e));

	}

	protected void handleInvalidatedResponse(String url) {
		logger.error(url+":invalidated http response");
	}

	protected boolean validateHttpResponse(HttpResponse httpResponse) {
		if (httpResponse == null) {
			logger.info("http response is null");
			return false;
		}
		if (httpResponse.getCode() == 200) {
			return true;
		}
		logger.info(httpResponse.getContent());
		return false;
	}

}
