package com.jsc.oscm.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 com.jsc.oscm.dao.UserInfoRepository;
import com.jsc.oscm.model.SecurityUserInfo;
import com.jsc.oscm.entity.UserInfo;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    UserInfoRepository userInfoRep;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(username);
        Example<UserInfo> example = Example.of(userInfo);
        Optional<UserInfo> userOptional = userInfoRep.findOne(example);
        if (userOptional.isPresent()) {
            userInfo = userOptional.get();
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("admin"));
            SecurityUserInfo securityUserInfo = new SecurityUserInfo(userInfo.getUserName().trim(), userInfo.getPassWord().trim(), grantedAuthorities);
            securityUserInfo.setIsAccountNonExpired(userInfo.getIsAccountNonExpired());
            securityUserInfo.setIsAccountNonLocked(userInfo.getIsAccountNonLocked());
            securityUserInfo.setIsCredentialsNonExpired(userInfo.getIsCredentialsNonExpired());
            securityUserInfo.setIsEnabled(userInfo.getIsEnabled());
            return securityUserInfo;
        } else {
            return null;
        }
    }

}
