package app.usluga;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import app.model.Uloga;
import app.rep.KorisnickiRep;
import app.usluga.web.transfer.Registracija;
import app.model.Korisnik;

@Service
public class Implementacija implements KorisnickaUsluga{

	private KorisnickiRep kr;
	
	@Autowired
	private BCryptPasswordEncoder enkoder;
	
	public Implementacija(KorisnickiRep kr) {
		super();
		this.kr=kr;
	}

	@Override
	public Korisnik save(Registracija r) throws UsernameNotFoundException {
		Korisnik k= new Korisnik(r.getFirstName(), 
				r.getLastName(), r.getEmail(),
				enkoder.encode(r.getPassword()), Arrays.asList(new Uloga("KORISNIK")));
		Korisnik k2=kr.findByEmail(k.getEmail());
		if(k2!=null) {
			throw new UsernameNotFoundException("Invalid Username or password");
		}
		
		return kr.save(k);
	}

	@Override
	public UserDetails loadUserByUsername(String ime) throws UsernameNotFoundException {
	
		Korisnik k = kr.findByEmail(ime);
		if(k == null) {
			throw new UsernameNotFoundException("Invalid username or password.");
		}
		return new org.springframework.security.core.userdetails.User(k.getEmail(), k.getLozinka(), mapRolesToAuthorities(k.getUloge()));		
	}
	
	private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Uloga> uloge){
		return uloge.stream().map(uloga -> new SimpleGrantedAuthority(uloga.getIme())).collect(Collectors.toList());
	}
	
}
