package org.yacos.auth;

import java.util.List;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.yacos.core.users.Role;
import org.yacos.core.users.User;
import org.yacos.web.system.session.SessionService;

public class UserDetails implements org.acegisecurity.userdetails.UserDetails {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String login;
	/**
	 * Password : used for authentication purpose only, is only writable
	 */
	private String password;
	/**
	 * First Name of the user
	 */
	private String firstName;
	/**
	 * Last name of the user
	 */
	private String lastName;
	/**
	 * Organization or lab the user belongs to
	 */
	private String organization;
	/**
	 * Active email (has to be used frequently) of the user
	 */
	private String email;
	
	public UserDetails(User user) {
		this.login = user.getLogin();
		this.password = user.getPassword();
		this.firstName = user.getFirstName();
		this.lastName = user.getLastName();
		this.organization = user.getOrganization();
		this.email = user.getEmail();
	}

	public GrantedAuthority[] getAuthorities() {
		Integer currentConferenceId = SessionService.getInstance().getCurrentConferenceId();
		
		GrantedAuthority[] authorities = null;
		
		if(currentConferenceId != null){
			List<Role> rolesList = SessionService.getInstance().getConferenceManager().getRoles(login, currentConferenceId);
			if(! rolesList.isEmpty()){
				authorities = new GrantedAuthority[rolesList.size()];
			}
			
			for(int i=0;i<rolesList.size();i++){
				authorities[i] = new GrantedAuthorityImpl("ROLE_"+rolesList.get(i).getType().name());
			}
		}
		return (GrantedAuthority[]) authorities;
	}

	public String getPassword() {
		return password;
	}

	public String getUsername() {
		return login;
	}

	public boolean isAccountNonExpired() {
		return true;
	}

	public boolean isAccountNonLocked() {
		return true;
	}

	public boolean isCredentialsNonExpired() {
		return true;
	}

	public boolean isEnabled() {
		return true;
	}
	
	public String getLogin() {
		return login;
	}
	
	public String getFirstName() {
		return firstName;
	}
	
	public String getLastName() {
		return lastName;
	}
	
	public String getEmail() {
		return email;
	}
	
	public String getOrganization() {
		return organization;
	}

}
