package gov.va.vss.config;

import java.time.LocalDate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;

import gov.va.vss.model.volunteer.Volunteer;
import gov.va.vss.service.VolunteerUserDetailsProvider;
import gov.va.vss.util.DateUtil;

public class VolunteerDaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

	@Autowired
	private VolunteerUserDetailsProvider volunteerUserDetailsProvider;

	@Value("${maxAllowedFailedLogins}")
	private int maxAllowedFailedLogins;
	@Value("${autoUnlockMinutes}")
	private int autoUnlockMinutes;
	@Value("${autoDisableAfterDays}")
	private int autoDisableAfterDays;

	public VolunteerDaoAuthenticationProvider() {
		setHideUserNotFoundExceptions(false);
	}

	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		try {
			String dob = (String) authentication.getCredentials();
			LocalDate d = LocalDate.parse(dob, DateUtil.TWO_DIGIT_DATE_ONLY_FORMAT);
			Volunteer v = (Volunteer) userDetails;
			if (v.getDateOfBirth() == null || !v.getDateOfBirth().equals(d))
				throw new BadCredentialsException("No volunteer found with that identifying code and date of birth.");
		} catch (Exception e) {
			if (e instanceof BadCredentialsException)
				throw e;

			throw new BadCredentialsException("No volunteer found with that identifying code and date of birth.");
		}
	}

	@Override
	@Transactional(readOnly = true)
	protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		Volunteer v = volunteerUserDetailsProvider.retrieveUser(username, authentication);
		return v;
	}

}
