package kr.co.uplus.ez.api.login;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import kr.co.uplus.ez.api.login.dto.AuthUser;
import kr.co.uplus.ez.common.data.Const;
import kr.co.uplus.ez.common.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	@Qualifier("sqlSessionTemplateDb1")
	private SqlSessionTemplate sqlSessionMaster;

	@Autowired
	@Qualifier("sqlSessionTemplateDb2")
	private SqlSessionTemplate sqlSessionSlave;

	@SuppressWarnings("unused")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		LoginMapper authUserMapper = sqlSessionMaster.getMapper(LoginMapper.class);

		logger.debug("username = [{}]", username);
		String corpId = null;
		if (username.indexOf(".") > -1) {
			String[] splts = username.split("\\.");
			corpId = splts[0];
			username = splts[1];
		}
        AuthUser user = authUserMapper.getByUsername(username);
        log.info("userPWD = {}",user.getPwd());
        if (corpId != null) {
        	user.setCorpId(corpId);
        }

        HttpServletRequest request = SpringUtils.getCurrentRequest();
        request.setAttribute(Const.KEY_LOAD_USER, user);

        logger.debug("user = [{}]", user);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }

		List<GrantedAuthority> roles = AuthorityUtils.createAuthorityList(user.getAutCd());
		logger.debug("roles = [{}]", roles);
		if (roles.isEmpty()) {
			roles = AuthorityUtils.createAuthorityList("1004");
		}

		user.setAuthorities(roles);
		logger.debug("user = [{}]", user);

		return user;
	}
}
