package br.com.vepo.datatransform.config;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import br.com.vepo.datatransform.model.User;
import br.com.vepo.datatransform.model.UserRepository;

@Component
public class DataTransformAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		User user = userRepository.findByUsername(authentication.getName());

		if (user != null && passwordEncoder.matches(authentication.getCredentials().toString(), user.getPassword())) {
			List<GrantedAuthority> grantedAuths = new ArrayList<>();
			for (String role : user.getRoles()) {
				grantedAuths.add(new SimpleGrantedAuthority(role));
			}
			return new UsernamePasswordAuthenticationToken(user, authentication.getName(), grantedAuths);
		} else {
			return null;
		}
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}
