package com.mason.server.security.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.mason.server.dao.jdo.UserDAO;
import com.mason.server.model.DbUser;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

/**
 * A custom service for retrieving users from a custom datasource, such as a
 * database.
 * <p>
 * This custom service must implement Spring's {@link UserDetailsService}
 */
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

	private UserDAO userDAO = new UserDAO();

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserDetails user = null;

		try {

			DbUser dbUser = userDAO.getByUsername(username);

			user = new User(dbUser.getUsername(), dbUser.getPassword(), true, true, true, true,
					getAuthorities(dbUser.getAccess()));

		} catch (Exception e) {
			throw new UsernameNotFoundException("Error in retrieving user");
		}
		
		return user;
	}

	public Collection<GrantedAuthority> getAuthorities(Integer access) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
		authList.add(new SimpleGrantedAuthority("ROLE_USER"));
		
		return authList;
	}
}
