package gov.va.vss.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import gov.va.shared.model.Permission;
import gov.va.shared.model.Role;
import gov.va.shared.model.Role.RoleType;
import gov.va.shared.service.impl.AbstractAppServiceImpl;
import gov.va.vss.model.volunteer.Volunteer;
import gov.va.vss.persistence.dao.volunteer.VolunteerDAO;

@Service
public class VolunteerUserDetailsProvider extends AbstractAppServiceImpl {

	@Autowired
	private VolunteerDAO volunteerDAO;

	public Volunteer retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) {
		List<Volunteer> vols = volunteerDAO.findByCriteria(null, null, null, false, false, username, null, null, null,
				null, null, null, null, null, null);
		if (vols.isEmpty())
			throw new UsernameNotFoundException("Sorry, that identifying code was not found.");
		Volunteer v = vols.get(0);

		Role volunteerRole = roleDAO.findByLookup(RoleType.VOLUNTEER);
		Set<Permission> permissions = volunteerRole.getPermissions();

		List<GrantedAuthority> allAuthorities = new ArrayList<>(permissions.size() + 1);
		allAuthorities.add(volunteerRole);
		allAuthorities.addAll(permissions);
		v.setAuthorities(Collections.unmodifiableList(allAuthorities));

		v.getStatus().getDescription();
		return v;
	}

}
