/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.system.security.service;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BadRequestException;
import easydo.technology.exception.BizException;
import easydo.technology.exception.EntityNotFoundException;
import easydo.technology.system.model.SysUser;
import easydo.technology.system.security.config.bean.LoginProperties;
import easydo.technology.system.security.service.dto.JwtUserDto;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private final JdbcClient jdbcClient;
    private final DataSource dataSource;
    private final LoginProperties loginProperties;
    public void setEnableCache(boolean enableCache) {
        this.loginProperties.setCacheEnable(enableCache);
    }

    /**
     * 用户信息缓存
     *
     * @see {@link UserCacheClean}
     */
    static Map<String, JwtUserDto> userDtoCache = new ConcurrentHashMap<>();

    @Override
    public JwtUserDto loadUserByUsername(String username) {
        boolean searchDb = true;
        JwtUserDto jwtUserDto = null;
        if (loginProperties.isCacheEnable() && userDtoCache.containsKey(username)) {
            jwtUserDto = userDtoCache.get(username);
            searchDb = false;
        }
        if (searchDb) {
            SysUser user = new SysUser();
            user.setUsername(username);
            try {
                user = jdbcClient.getJdbcModel(user);
            } catch (EntityNotFoundException e) {
                // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
                throw new UsernameNotFoundException("", e);
            } catch (Exception e) {
                throw new BizException(e.getMessage());
            }
            if (user == null) {
                throw new UsernameNotFoundException("");
            } else {
                jwtUserDto = new JwtUserDto(
                        user,
                        getUserDeptIds(user),
                        mapToGrantedAuthorities(user)
                );
                userDtoCache.put(username, jwtUserDto);
            }
        }
        return jwtUserDto;
    }

    private List<Long> getUserDeptIds(SysUser user) {
        // 用于存储部门id
        Set<Long> deptIds = new HashSet<>();
        deptIds.add(user.getDeptId());
        return new ArrayList<>(deptIds);
    }

    private List<GrantedAuthority> mapToGrantedAuthorities(SysUser user) {
        Set<String> permissions = new HashSet<>();
        permissions.add("admin");
        return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }
}
