/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portlet.relatedassets.filter;

import com.liferay.portal.kernel.servlet.DynamicServletRequest;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.util.WebKeys;
import com.liferay.portlet.RenderParametersPool;

import java.io.IOException;

import java.util.Map;

import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.filter.FilterChain;
import javax.portlet.filter.FilterConfig;
import javax.portlet.filter.RenderFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @author Minhchau Dang
 * @author Preston Crary
 */
public class RelatedAssetsRenderParametersPortletFilter
	implements RenderFilter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(
			RenderRequest renderRequest, RenderResponse renderResponse,
			FilterChain filterChain)
		throws IOException, PortletException {

		HttpServletRequest request = PortalUtil.getHttpServletRequest(
			renderRequest);

		if (request.getAttribute(WebKeys.LAYOUT_ASSET_ENTRY) == null) {
			clearDynamicServletRequestParameters(request);

			clearRenderRequestParameters(renderRequest, request);
		}

		filterChain.doFilter(renderRequest, renderResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) {
	}

	protected void clearDynamicServletRequestParameters(
		HttpServletRequest request) {

		DynamicServletRequest dynamicServletRequest = null;

		while (request instanceof HttpServletRequestWrapper) {
			if (request instanceof DynamicServletRequest) {
				dynamicServletRequest = (DynamicServletRequest)request;

				break;
			}

			HttpServletRequestWrapper httpServletRequestWrapper =
				(HttpServletRequestWrapper)request;

			request =
				(HttpServletRequest)httpServletRequestWrapper.getRequest();
		}

		if (dynamicServletRequest != null) {
			Map<String, String[]> dynamicParameterMap =
				dynamicServletRequest.getDynamicParameterMap();

			dynamicParameterMap.clear();
		}
	}

	protected void clearRenderRequestParameters(
		RenderRequest renderRequest, HttpServletRequest request) {

		ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(
			WebKeys.THEME_DISPLAY);

		String portletId = PortalUtil.getPortletId(renderRequest);

		RenderParametersPool.clear(request, themeDisplay.getPlid(), portletId);
	}

}