package com.eactive.eai.authserver.dao;

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

import org.apache.commons.lang3.StringUtils;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.authserver.dao.UserLoader;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authserver.UserEntity;

@Service
@Transactional
public class UserDAO extends BaseDAO {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	@Autowired
	private UserLoader userLoader;

	public UserDetails getUserByUserId(String userId) throws DAOException {
		try {
			UserEntity userEntity = userLoader.getById(userId);

			if (userEntity != null) {
				return new User(userId, userEntity.getPassword(), assignAuthorities(userEntity.getAuthorities()));
			}
			return null;

		} catch (Exception e) {
			throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAIAAC009"));
		}
	}

	public List<GrantedAuthority> assignAuthorities(String roleStr) {
		List<GrantedAuthority> authorities = new ArrayList<>();

		if (StringUtils.isBlank(roleStr)) {
			return authorities;
		}

		for (String role : StringUtils.split(roleStr, ",")) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
}
