/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.web.servlet.config.annotation;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;

import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.accept.ContentNegotiationStrategy;

/**
 * Helps with configuring a {@link ContentNegotiationManager}.
 *
 * <p>By default strategies for checking the extension of the request path and
 * the {@code Accept} header are registered. The path extension check will perform
 * lookups through the {@link ServletContext} and the Java Activation Framework
 * (if present) unless {@linkplain #mediaTypes(Map) media types} are configured.
 *
 * @author Rossen Stoyanchev
 * @since 3.2
 */
public class ContentNegotiationConfigurer {

	private final ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean();

	private final Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>();


	/**
	 * Class constructor with {@link javax.servlet.ServletContext}.
	 */
	public ContentNegotiationConfigurer(ServletContext servletContext) {
		this.factoryBean.setServletContext(servletContext);
	}

	/**
	 * Indicate whether the extension of the request path should be used to determine
	 * the requested media type with the <em>highest priority</em>.
	 * <p>By default this value is set to {@code true} in which case a request
	 * for {@code /hotels.pdf} will be interpreted as a request for
	 * {@code "application/pdf"} regardless of the {@code Accept} header.
	 */
	public ContentNegotiationConfigurer favorPathExtension(boolean favorPathExtension) {
		this.factoryBean.setFavorPathExtension(favorPathExtension);
		return this;
	}

	/**
	 * Add a mapping from a key, extracted from a path extension or a query
	 * parameter, to a MediaType. This is required in order for the parameter
	 * strategy to work. Any extensions explicitly registered here are also
	 * whitelisted for the purpose of Reflected File Download attack detection
	 * (see Spring Framework reference documentation for more details on RFD
	 * attack protection).
	 * <p>The path extension strategy will also try to use
	 * {@link ServletContext#getMimeType} and JAF (if present) to resolve path
	 * extensions. To change this behavior see the {@link #useJaf} property.
	 * @param extension the key to look up
	 * @param mediaType the media type
	 * @see #mediaTypes(Map)
	 * @see #replaceMediaTypes(Map)
	 */
	public ContentNegotiationConfigurer mediaType(String extension, MediaType mediaType) {
		this.mediaTypes.put(extension, mediaType);
		return this;
	}

	/**
	 * An alternative to {@link #mediaType} with a Map of registrations to add.
	 */
	public ContentNegotiationConfigurer mediaTypes(Map<String, MediaType> mediaTypes) {
		if (mediaTypes != null) {
			this.mediaTypes.putAll(mediaTypes);
		}
		return this;
	}

	/**
	 * Add mappings from file extensions to media types replacing any previous mappings.
	 * <p>If this property is not set, the Java Action Framework, if available, may
	 * still be used in conjunction with {@link #favorPathExtension(boolean)}.
	 */
	public ContentNegotiationConfigurer replaceMediaTypes(Map<String, MediaType> mediaTypes) {
		this.mediaTypes.clear();
		mediaTypes(mediaTypes);
		return this;
	}

	/**
	 * Whether to ignore requests that have a file extension that does not match
	 * any mapped media types. Setting this to {@code false} will result in a
	 * {@code HttpMediaTypeNotAcceptableException} when there is no match.
	 *
	 * <p>By default this is set to {@code true}.
	 */
	public ContentNegotiationConfigurer ignoreUnknownPathExtensions(boolean ignore) {
		this.factoryBean.setIgnoreUnknownPathExtensions(ignore);
		return this;
	}

	/**
	 * Indicate whether to use the Java Activation Framework as a fallback option
	 * to map from file extensions to media types. This is used only when
	 * {@link #favorPathExtension(boolean)} is set to {@code true}.
	 * <p>The default value is {@code true}.
	 * @see #parameterName
	 * @see #mediaTypes(Map)
	 */
	public ContentNegotiationConfigurer useJaf(boolean useJaf) {
		this.factoryBean.setUseJaf(useJaf);
		return this;
	}

	/**
	 * Indicate whether a request parameter should be used to determine the
	 * requested media type with the <em>2nd highest priority</em>, i.e.
	 * after path extensions but before the {@code Accept} header.
	 * <p>The default value is {@code false}. If set to to {@code true}, a request
	 * for {@code /hotels?format=pdf} will be interpreted as a request for
	 * {@code "application/pdf"} regardless of the {@code Accept} header.
	 * <p>To use this option effectively you must also configure the MediaType
	 * type mappings via {@link #mediaTypes(Map)}.
	 * @see #parameterName(String)
	 */
	public ContentNegotiationConfigurer favorParameter(boolean favorParameter) {
		this.factoryBean.setFavorParameter(favorParameter);
		return this;
	}

	/**
	 * Set the parameter name that can be used to determine the requested media type
	 * if the {@link #favorParameter(boolean)} property is {@code true}.
	 * <p>The default parameter name is {@code "format"}.
	 */
	public ContentNegotiationConfigurer parameterName(String parameterName) {
		this.factoryBean.setParameterName(parameterName);
		return this;
	}

	/**
	 * Indicate whether the HTTP {@code Accept} header should be ignored altogether.
	 * If set the {@code Accept} header is checked at the
	 * <em>3rd highest priority</em>, i.e. after the request path extension and
	 * possibly a request parameter if configured.
	 * <p>By default this value is set to {@code false}.
	 */
	public ContentNegotiationConfigurer ignoreAcceptHeader(boolean ignoreAcceptHeader) {
		this.factoryBean.setIgnoreAcceptHeader(ignoreAcceptHeader);
		return this;
	}

	/**
	 * Set the default content type to use when no content type was requested.
	 * <p>Note that internally this method creates and adds a
	 * {@link org.springframework.web.accept.FixedContentNegotiationStrategy
	 * FixedContentNegotiationStrategy}. Alternatively you can also provide a
	 * custom strategy via {@link #defaultContentTypeStrategy}.
	 */
	public ContentNegotiationConfigurer defaultContentType(MediaType defaultContentType) {
		this.factoryBean.setDefaultContentType(defaultContentType);
		return this;
	}

	/**
	 * Configure a custom {@link ContentNegotiationStrategy} to use to determine
	 * the default content type to use when no content type was requested.
	 * <p>However also consider using {@link #defaultContentType} which provides
	 * a simpler alternative to doing the same.
	 * @since 4.1.2
	 */
	public ContentNegotiationConfigurer defaultContentTypeStrategy(ContentNegotiationStrategy defaultStrategy) {
		this.factoryBean.setDefaultContentTypeStrategy(defaultStrategy);
		return this;
	}

	/**
	 * Return the configured {@link ContentNegotiationManager} instance
	 */
	protected ContentNegotiationManager getContentNegotiationManager() throws Exception {
		if (!this.mediaTypes.isEmpty()) {
			this.factoryBean.addMediaTypes(mediaTypes);
		}
		this.factoryBean.afterPropertiesSet();
		return this.factoryBean.getObject();
	}

}
