package com.mx.cneeds.server.anthorization.service;

import com.mx.cneeds.common.dto.UserDto;
import com.mx.cneeds.server.anthorization.client.UserClient;
import com.mx.cneeds.server.entity.SysUserEntity;
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.User;
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.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private UserClient userClient;
	
	/** (non-Javadoc)
	 * @see UserDetailsService#loadUserByUsername(String)
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		SysUserEntity sysUserEntity = sysUserService.queryUserByUsername(username);
		if (sysUserEntity == null){
			return null;
		}

		UserDto userDto = userClient.userInfo(username);

		List<GrantedAuthority> authorities = new ArrayList<>();

		if (sysUserEntity.getUserId() == 1){

			authorities.add(new SimpleGrantedAuthority("ROLE_admin"));

		}else {

			List<String> funcPerms = userDto.getFuncPerms();
			funcPerms.forEach( str -> {
				authorities.add(new SimpleGrantedAuthority("ROLE_"+str));
			});

		}

		return new User(username, sysUserEntity.getPassword(), authorities);
	}

}