package premium_store.service;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import premium_store.model.GameClient;
import premium_store.repository.GameClientRepository;
import premium_store.util.validation.ValidatorUtil;

import javax.validation.ValidationException;
import java.util.Collections;
import java.util.Objects;

@Service
public class UserService implements UserDetailsService {
    private final GameClientRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final ValidatorUtil validatorUtil;

    public UserService(GameClientRepository userRepository,
                       PasswordEncoder passwordEncoder,
                       ValidatorUtil validatorUtil) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.validatorUtil = validatorUtil;
    }

    public GameClient findByLogin(String login) {
        return userRepository.findOneByLoginIgnoreCase(login);
    }

    public GameClient createUser(String login, String password, String passwordConfirm) {
        if (findByLogin(login) != null) {
            throw new ValidationException(String.format("User '%s' already exists", login));
        }

        final GameClient user = new GameClient(login, passwordEncoder.encode(password), 0);

        validatorUtil.validate(user);

        if (!Objects.equals(password, passwordConfirm)) {
            throw new ValidationException("Passwords not equals");
        }

        return userRepository.save(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final GameClient userEntity = findByLogin(username);

        if (userEntity == null) {
            throw new UsernameNotFoundException(username);
        }

        return new org.springframework.security.core.userdetails.User(
                userEntity.getNickName(), userEntity.getEmail(), Collections.emptyList());
    }

}
