package com.bankaudit.security;

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

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.bankaudit.model.MaintRoleEntitlement;
import com.bankaudit.model.MaintUsergroupRoles;
import com.bankaudit.model.User;

public class CustomUserDetails extends User implements UserDetails {


	private static final long serialVersionUID = 1L;
	
	private Set<MaintUsergroupRoles> maintUsergroupRoles;
	
	
	public CustomUserDetails(User user ,Set<MaintUsergroupRoles>  maintUsergroupRoles) {
		super(user);
		this.maintUsergroupRoles=maintUsergroupRoles;
	}
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		
		
		List<GrantedAuthority> roleAuthorities = new ArrayList<GrantedAuthority>();

		if(maintUsergroupRoles!=null && !maintUsergroupRoles.isEmpty()){
			GrantedAuthority grantedAuthority=null;
			for (MaintUsergroupRoles maintUsergroupRole : maintUsergroupRoles) {
				 grantedAuthority = new GrantedAuthority() {
					private static final long serialVersionUID = 1L;
					@Override
					public String getAuthority() {
						return maintUsergroupRole.getUgRoleCode()+"-"+maintUsergroupRole.getUgRoleName();
					}
				};
				roleAuthorities.add(grantedAuthority);
				
				if(maintUsergroupRole.getMaintRoleEntitlements()!=null){
					for (MaintRoleEntitlement maintRoleEntitlement : maintUsergroupRole.getMaintRoleEntitlements()) {
						 grantedAuthority = new GrantedAuthority() {
							private static final long serialVersionUID = 1L;
							@Override
							public String getAuthority() {
								return "ROLE_"+maintRoleEntitlement.getFunctionId();
							}
						};
						roleAuthorities.add(grantedAuthority);
						
						
					}
				}
				
			}
		}
		
		return roleAuthorities;
	}

	
	
	@Override
	public String getUsername() {
		return getUserId();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	@Override
	public boolean isEnabled() {
		return true;
	}

}
