package com.skr.mdm.filter;

import com.skr.mdm.authentication.TokenExpireException;
import com.skr.mdm.authentication.admin.AccessDeniedAuthenticationHandler;
import com.skr.mdm.authentication.admin.AdminAuthenticationEntryPoint;
import com.skr.mdm.authentication.admin.IllegalRequestException;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.service.AdminTokenService;
import com.skr.mdm.util.AntiReplayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author nfq
 */
@Component
@Slf4j
public class ClientAdminTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_KEY = "token";
    private static final String LOGIN_URI = "/login";
    private static final String ANDROID = "android";
    private static final String USER_AGENT = "User-Agent";

    @Autowired
    private AdminTokenService tokenService;
    @Autowired
    private AdminAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private AccessDeniedAuthenticationHandler accessDeniedAuthenticationHandler;
    @Autowired
    private AntiReplayUtil antiReplayUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 防重放
//            if (!StringUtils.equals(VERIFY_CODE_URI, request.getRequestURI())) {
//                antiReplayUtil.adminAntiReplay(request);
//            }
        } catch (IllegalRequestException e) {
            accessDeniedAuthenticationHandler.handle(request, response, e);
            return;
        }
        String method = request.getMethod();
        if (StringUtils.equals(LOGIN_URI, request.getRequestURI()) && StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), method.toLowerCase())) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = getToken(request);
        if (StringUtils.isNotBlank(token)) {
            LoginAdminDTO loginAdminDTO = null;
            try {
                loginAdminDTO = tokenService.getLoginAdmin(token);
                if (loginAdminDTO == null) {
                    filterChain.doFilter(request, response);
                    return;
                }
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginAdminDTO,
                        null, loginAdminDTO.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (TokenExpireException e) {
                authenticationEntryPoint.commence(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 根据参数或者header获取JWTtoken
     *
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        String token = request.getParameter(TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            token = request.getHeader(TOKEN_KEY);
        }
        return token;
    }

}
