package com.kingdee.eas.custom.integration.base.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;

/**
 * 未在 web.xml 声明时，编程式注册 CallbackSuffixCompatFilter，覆盖整个 /auth/*。
 */
@WebListener
public class CallbackSuffixCompatFilterRegistrar implements ServletContextListener {

    private static final Logger log = LoggerFactory.getLogger(CallbackSuffixCompatFilterRegistrar.class);

    private static final String FILTER_NAME = "callbackSuffixCompatFilter";

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        if (context.getFilterRegistration(FILTER_NAME) != null) {
            return;
        }
        FilterRegistration.Dynamic registration =
                context.addFilter(FILTER_NAME, new CallbackSuffixCompatFilter());
        if (registration == null) {
            log.warn("Failed to register {}", FILTER_NAME);
            return;
        }
        registration.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST), false, "/auth/*");
        log.info("Registered {} for /auth/*", FILTER_NAME);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }
}
