package org.codiki.core.services;

import java.security.Principal;
import java.util.Optional;

import org.codiki.core.entities.persistence.User;
import org.codiki.core.repositories.UserRepository;
import org.codiki.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;

@Service
public class UserService {
	private static final String MSG_BAD_CREDENTIALS = "Adresse email ou mot de passe incorrect.";

	private final UserRepository userRepository;

	public UserService(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public User checkCredentials(final String email, final String password) throws BadCredentialsException {
		final Optional<User> optUser = userRepository.findByEmail(email);

		// If no user exists with the given email of if the given password doesn't match
		// to the user password, we throw an exception.
		if(optUser.isEmpty() || !StringUtils.compareHash(password, optUser.get().getPassword())) {
			throw new BadCredentialsException(MSG_BAD_CREDENTIALS);
		}
		
		return optUser.get();
	}
	
	public Optional<User> getUserByPrincipal(final Principal pPrincipal) {
		Optional<User> result = Optional.empty();

		if(pPrincipal != null) {
			SecurityContextHolder.getContext().getAuthentication();
			result = userRepository.findByEmail(pPrincipal.getName());
		}

		return result;
	}
}
