package org.ros.chatto.security;

import java.util.Optional;
import java.util.Set;

import org.ros.chatto.model.ChatUser;
import org.ros.chatto.model.UserRole;
import org.ros.chatto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

	@Autowired
	private final UserService userService;

	@Override
	public UserDetails loadUserByUsername(final String username) {
		log.trace("User Details - loading with username: {}", username);
		Optional<ChatUser> user = userService.getUser(username);

		if (!user.isPresent()) {
			log.warn("Request for unknown user {}", username);
			throw new UsernameNotFoundException(username);
		}

		ChatUser user2 = user.get();

		Set<UserRole> userRoles = user2.getUserRoles();

		return User.withUsername(user2.getUserName())
				.password(user2.getPassword())
				.roles(userRoles.stream().map(ur -> ur.getRole().getName())
						.toArray(size -> new String[size]))
				.build();
	}
}
