package com.ffii.core.config.auth;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.ffii.core.user.service.UserAttemptService;
import com.ffii.core.user.service.UserService;

/** @author Fung */
@Component
public class FailureHandler implements AuthenticationFailureHandler {

	private final int AUTO_LOCK_COUNT;
	private UserAttemptService userAttemptService;
	private UserService userService;

	public FailureHandler(
			@Value("${app.login.attempt-lock:5}") int autoLockCount,
			UserAttemptService userAttemptService,
			UserService userService) {
		this.AUTO_LOCK_COUNT = autoLockCount;
		this.userAttemptService = userAttemptService;
		this.userService = userService;
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		String username = request.getParameter("username");

		userAttemptService.loginFailure(username);

		if (userAttemptService.findAttempt(username) >= AUTO_LOCK_COUNT) {
			userService.findByUsername(username).ifPresent(user -> {
				if (!user.isLocked()) {
					user.setLocked(Boolean.TRUE);
					userService.save(user);
				}
			});
		}

		if (exception instanceof LockedException ||
				exception instanceof DisabledException ||
				exception instanceof AccountExpiredException ||
				exception instanceof CredentialsExpiredException) {
			response.setStatus(HttpStatus.FORBIDDEN.value());
		} else {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
		}
	}

}
