package com.ruoyi.framework.web.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;

/**
 * Local debug only: redirect /profile/** from 127.0.0.1/localhost to remote host.
 * Enabled only when ruoyi.isLocalDebug=true.
 */
public class LocalProfileProxyFilter extends OncePerRequestFilter
{
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request)
    {
        if (!RuoYiConfig.isLocalDebug())
        {
            return true;
        }
        String host = request.getServerName();
        if (!"127.0.0.1".equals(host) && !"localhost".equals(host))
        {
            return true;
        }
        String path = resolvePath(request);
        return path == null || !path.startsWith(Constants.RESOURCE_PREFIX + "/");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException
    {
        String path = resolvePath(request);
        String qs = request.getQueryString();
        String remoteHost = RuoYiConfig.getLocalRemoteHost();
        if (StringUtils.isEmpty(remoteHost))
        {
            remoteHost = "129.28.164.235";
        }
        String remoteUrl = "http://" + remoteHost + path + (StringUtils.isNotEmpty(qs) ? "?" + qs : "");
        response.setStatus(HttpServletResponse.SC_FOUND);
        response.setHeader("Location", remoteUrl);
    }

    private String resolvePath(HttpServletRequest request)
    {
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (StringUtils.isNotEmpty(contextPath) && uri != null && uri.startsWith(contextPath))
        {
            return uri.substring(contextPath.length());
        }
        return uri;
    }
}
