package org.bench4q.web.masterMessager;

import java.util.HashMap;
import java.util.Map;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AuthorizeResponseModel;
import org.bench4q.share.models.master.RegisterResponseModel;
import org.springframework.stereotype.Component;

@Component
public class UserMessager extends MasterMessager {

	public UserMessager() {
		super(MasterAddressManamger.getMasterAddress() + "/user");
	}

	public RegisterResponseModel register(String userName, String password,
			String scope) {
		String url = this.getBaseUrl() + "/register";
		Map<String, String> params = new HashMap<String, String>();
		params.put("userName", userName);
		params.put("password", password);
		params.put("scope", scope);
		HttpResponse httpResponse = null;
		try {
			httpResponse = this.getHttpRequester().sendGet(url, params, null);
			if (!validateHttpResponse(httpResponse)) {
				return null;
			}
			return (RegisterResponseModel) MarshalHelper.unmarshal(
					RegisterResponseModel.class, httpResponse.getContent());

		} catch (Exception e) {
			this.handleException(httpResponse, e);
			RegisterResponseModel registerResponseModel = new RegisterResponseModel();
			registerResponseModel.setSuccess(false);
			return registerResponseModel;
		}
	}

	public AuthorizeResponseModel adminLogin(String userName, String password) {
		String url = this.getBaseUrl() + "/adminAuthorize";
		return getAuthorizeResponseModel(url, makeParams(userName, password));
	}

	public AuthorizeResponseModel normalLogin(String userName, String password) {
		String url = this.getBaseUrl() + "/normalAuthorize";

		return getAuthorizeResponseModel(url, makeParams(userName, password));
	}

	public AuthorizeResponseModel deleteUser(String userName) {
		String url = this.getBaseUrl() + "/deleteUser" + "/" + userName;
		return getAuthorizeResponseModel(url, null);
	}

	private Map<String, String> makeParams(String userName, String password) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("userName", userName);
		params.put("password", password);
		return params;
	}

	private AuthorizeResponseModel getAuthorizeResponseModel(String url,
			Map<String, String> params) {
		HttpResponse httpResponse = null;
		try {
			httpResponse = this.getHttpRequester().sendGet(url, params, null);
			if (!validateHttpResponse(httpResponse))
				return null;
			return (AuthorizeResponseModel) MarshalHelper.unmarshal(
					AuthorizeResponseModel.class, httpResponse.getContent());

		} catch (Exception e) {
			this.handleException(httpResponse, e);
			return createFailAuthorizeResponseModel();
		}

	}

	private AuthorizeResponseModel createFailAuthorizeResponseModel() {
		AuthorizeResponseModel authorizeResponseModel = new AuthorizeResponseModel();
		authorizeResponseModel.setSuccess(false);
		return authorizeResponseModel;
	}
}
