package org.bench4q.master.api;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.domain.service.auth.AuthenticationManager;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.models.ErrorResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

public abstract class BaseController {
	private HttpServletRequest request;
	private AuthenticationManager authenticationManager;
	protected static final String HAVE_NO_POWER = "Have no power";
	protected static final String EXCEPTION_HAPPEND = "Exception happened";
	private Logger logger = Logger.getLogger(BaseController.class);

	protected HttpServletRequest getRequest() {
		return request;
	}

	@Autowired
	protected void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	protected AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	@Autowired
	protected void setAuthenticationManager(
			AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	@ExceptionHandler(Bench4QException.class)
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ResponseBody
	public ErrorResponseModel handleException(Bench4QException e) {
		logger.error(ExceptionLog.getStackTrace(e));
		return ErrorResponseModel.buildErrorResponse(e.getCode(),
				e.getMessage(), e.getResource());
	}

	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ResponseBody
	public ErrorResponseModel handleException(RuntimeException e) {
		logger.info(ExceptionLog.getStackTrace(e));
		logger.info(e.getCause());
		return ErrorResponseModel.buildErrorResponse("RUNTIME_EXCEPTION",
				e.getMessage(), "");
	}

	protected User getPrincipal() {
		return this.getAuthenticationManager().getPrincipal(this.getRequest());
	}

	protected boolean checkScope(byte scope) {
		return this.getAuthenticationManager().checkScope(this.getRequest(),
				scope);
	}

	protected void guardHasAuthentication(String extraMessage, String apiUrl)
			throws Bench4QException {
		if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
			throw new Bench4QException(HAVE_NO_POWER, extraMessage, apiUrl);
		}
	}

}
