package kr.co.uplus.ez.config.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;

public class VueStaticFilter extends GenericFilterBean {

	// Vuejs router url prefix 선언
	private static final String[] FRONTEND_URLS = { "/view", "/login", "/favicon", "/custMgt", "/sysMgt", "/attractMgt",
			"/servMgt", "/calculate", "/channelMgt", "/sendNumMgt", "/mntrng", "/riskMgt", "/stats" ,"/homeMgt" };

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (shouldExclude(request)) {
			chain.doFilter(request, response);
		} else {
			// vuejs에 해당하는 페이지는 index를 바라보도록 전달
			((HttpServletRequest) request).getRequestDispatcher("/").forward(request, response);
		}
	}

	private boolean shouldExclude(ServletRequest req) {
		boolean isEx = true;
		if (req instanceof HttpServletRequest) {
			HttpServletRequest hreq = (HttpServletRequest) req;
			if (Arrays.stream(FRONTEND_URLS).anyMatch(s -> hreq.getRequestURI().startsWith(s))) {
				return false;
			}
		}
		return isEx;
	}

}