/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.web.view.freemarker;


import com.ffii.core.setting.service.SettingsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

/**
 * FreeMarker view resolver which extends Spring's {@link AbstractTemplateViewResolver}.
 * <p>
 * Allows response's character encoding to be explicitly set (default to <code>UTF-8</code> if not set), so that it is not necessary to set it together at the
 * {@link #setContentType(String)} method.
 * <p>
 * The default suffix is set to <code>.ftl</code>
 *
 * @see FreeMarkerView
 *
 * @author Patrick
 */
public class FreeMarkerViewResolver extends AbstractTemplateViewResolver {

	/** Default response's character encoding is <code>UTF-8</code> */
	private static final String DEFAULT_RESPONSE_ENCODING = "UTF-8";

	/** Default suffix for FreeMarker template is <code>.ftl</code> */
	private static final String DEFAULT_SUFFIX = ".ftl";

	private String responseEncoding = DEFAULT_RESPONSE_ENCODING;

	@Autowired
	private SettingsService settingsService;

	public String getResponseEncoding() {
		return responseEncoding;
	}

	public void setResponseEncoding(String responseEncoding) {
		this.responseEncoding = responseEncoding;
	}

	/**
	 * Default constructor
	 * <p>
	 * 1. Sets default viewClass to {@link #requiredViewClass}.<br />
	 * 2. Sets default suffix to {@link #DEFAULT_SUFFIX}
	 *
	 * @see #setViewClass
	 * @see #setSuffix
	 */
	public FreeMarkerViewResolver() {
		setViewClass(requiredViewClass());
		setSuffix(DEFAULT_SUFFIX);
	}

	/**
	 * Requires {@link FreeMarkerView}.
	 */
	@Override
	protected Class<?> requiredViewClass() {
		return FreeMarkerView.class;
	}

	@Override
	protected AbstractUrlBasedView buildView(String viewName) throws Exception {
		FreeMarkerView view = (FreeMarkerView) super.buildView(viewName);
		view.setResponseEncoding(getResponseEncoding());
		view.setSettingsService(settingsService);
		return view;
	}

}
