package com.njzscloud.common.security.support;

import com.njzscloud.common.security.handler.LoginPostHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextRepository;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 配置器
 */
public class CombineAuthenticationConfigurer extends AbstractHttpConfigurer<CombineAuthenticationConfigurer, HttpSecurity> {

    /**
     * 登陆预处理器
     */
    private final Collection<LoginPreparer> loginPreparers = new ArrayList<>();
    /**
     * 认证管理器
     */
    private AuthenticationManager authenticationManager;
    /**
     * 登陆后置处理器
     */
    private LoginPostHandler loginPostHandler;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        SecurityContextRepository securityContextRepository = builder.getSharedObject(SecurityContextRepository.class);
        CombineAuthenticationFilter filter = new CombineAuthenticationFilter(loginPreparers, authenticationManager, loginPostHandler, securityContextRepository);
        builder.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 添加登陆预处理器
     *
     * @param loginPreparer 登陆预处理器
     * @return 配置器对象
     */
    public CombineAuthenticationConfigurer addLoginPreparer(LoginPreparer loginPreparer) {
        loginPreparers.add(loginPreparer);
        return this;
    }

    /**
     * 添加登陆预处理器
     *
     * @param loginPreparers 登陆预处理器
     * @return 配置器对象
     */
    public CombineAuthenticationConfigurer loginPreparers(Collection<LoginPreparer> loginPreparers) {
        this.loginPreparers.addAll(loginPreparers);
        return this;
    }

    /**
     * 设置认证管理器
     *
     * @param authenticationManager 认证管理器
     * @return 配置器对象
     * @see AbstractAuthenticationProvider
     */
    public CombineAuthenticationConfigurer authenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        return this;
    }

    /**
     * 设置登录历史记录器
     *
     * @param loginHistoryRecorder 登录历史记录器
     * @return 配置器对象
     * @see DefaultLoginHistoryRecorder
     */
    public CombineAuthenticationConfigurer loginHistoryRecorder(LoginHistoryRecorder loginHistoryRecorder) {
        this.loginPostHandler = new LoginPostHandler(loginHistoryRecorder);
        return this;
    }
}
