package egovframework.config;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Setter
@Configuration
@RequiredArgsConstructor
public class EgovConfigWeb implements WebMvcConfigurer, ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/plugins/**")
			.addResourceLocations("/resources/plugins/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
		registry.addResourceHandler("/css/**")
			.addResourceLocations("/resources/css/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
		registry.addResourceHandler("/img/**")
			.addResourceLocations("/resources/img/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
		registry.addResourceHandler("/js/**")
			.addResourceLocations("/resources/js/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
		registry.addResourceHandler("/xit/**")
			.addResourceLocations("/resources/xit/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
		registry.addResourceHandler("/font/**")
			.addResourceLocations("/resources/font/")
			.setCacheControl(CacheControl.noCache().mustRevalidate());
	}

	/**
	 * 브라우저 캐시 방지 Interceptor 등록
	 * 중요로직: 모든 요청에 대해 캐시 방지 헤더를 추가하여 브라우저 뒤로가기 시에도 항상 최신 데이터를 표시한다.
     * js, jsp, css 즉각 반영안됨, 주석처리
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptor() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
				// 중요로직: HTTP 캐시 방지 헤더 설정
				response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
				response.setHeader("Pragma", "no-cache"); // HTTP 1.0
				response.setDateHeader("Expires", 0); // Proxies
				return true;
			}
		}).addPathPatterns("/**"); // 모든 경로에 적용
	}

	/**
	 * Exception handling is now done using @ControllerAdvice in EgovExceptionAdvice class.
	 * The SimpleMappingExceptionResolver approach has been replaced with a more modern approach.
	 *
	 * @see egovframework.exception.EgovExceptionAdvice
	 */
	@Override
	public void configureHandlerExceptionResolvers(@Nullable List< HandlerExceptionResolver> resolvers) {
		// Exception handling is now done using @ControllerAdvice
	}

	@Bean
	public UrlBasedViewResolver viewResolver() {
		UrlBasedViewResolver tilesViewResolver = new UrlBasedViewResolver();
		tilesViewResolver.setViewClass(TilesView.class);
		tilesViewResolver.setOrder(1);
		return tilesViewResolver;
	}

	@Bean
	public TilesConfigurer tilesConfigurer() {
		TilesConfigurer tilesConfigurer = new TilesConfigurer();
		tilesConfigurer.setDefinitions(
				"/WEB-INF/tiles/tiles.xml"
		);
		tilesConfigurer.setCheckRefresh(true);
		return tilesConfigurer;
	}

	@Bean
	public InternalResourceViewResolver internalResourceViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		resolver.setOrder(2);
		return resolver;
	}


}
