package gov.va.med.esr.webservices.jaxws.spring.security;

import gov.va.med.esr.model.ServiceUser;
import gov.va.med.esr.service.UserService;
import gov.va.med.esr.webservices.jaxws.spring.interceptor.MessageContextHolder;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.security.PasswordEncryptionService;


import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class EEUserDetailsService extends AbstractComponent implements UserDetailsService {

	private UserService userService;

	private PasswordEncryptionService passwordEncryptionService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		ServiceUserDetails user = null;

		try {
			ServiceUser serviceUser = userService.getUserByUserName(userName);

			if (serviceUser == null)
				return null;

			MessageContextHolder.setServiceUser(serviceUser);
			
			user = new ServiceUserDetails();
			user.setUsername(serviceUser.getUserName());

			String encryptedPassword = serviceUser.getPassword();

			logger.debug("Encrypted Password = " + encryptedPassword);

			String decryptedPassword = passwordEncryptionService
					.decryptPassword(encryptedPassword);
			logger.debug("decryptedPassword = [PROTECTED]");

			user.setPassword(decryptedPassword);
			user.setAccountNonExpired(serviceUser.isActive());
		} catch (ServiceException se) {
			se.printStackTrace();
			logger.error("Exception to get User Object", se);
		}
		//passwordEncryptionService.  user.getPassword()
		return user;

	}

	public PasswordEncryptionService getPasswordEncryptionService() {
		return passwordEncryptionService;
	}

	public void setPasswordEncryptionService(
			PasswordEncryptionService passwordEncryptionService) {
		this.passwordEncryptionService = passwordEncryptionService;
	}

}
