package app.usluga;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
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.context.SecurityContextHolder;
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;
import app.model.Oglas;

@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("InKKKKKKKKKKKKKord");

		}

		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(),k.getId()));
	}
	
	private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Uloga> uloge,long id)
	{
		if(id==1)
		return uloge.stream().map(uloga -> new SimpleGrantedAuthority("ADMIN")).collect(Collectors.toList());
		else
			return uloge.stream().map(uloga -> new SimpleGrantedAuthority("KORISNIK")).collect(Collectors.toList());
	}
	
	
	@Override
	public List<Korisnik>izlistaj(){
		 List<Korisnik> lista= kr.findAll();
		 Korisnik k = kr.findById(Long.valueOf(1)).get();
		 lista.remove(k);
		 return lista;
	}
	
	@Override
	public void izbrisiKorisnika(int id) {
		this.kr.deleteById((long) id);
	}
}
