/*******************************************************************************
 * 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 java.io.IOException;
import java.util.Map;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.csrf.CsrfToken;

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

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
 * FreeMarker view which extends Spring's {@link org.springframework.web.servlet.view.freemarker.FreeMarkerView}.
 * <p>
 * Enforce response's character encoding using {@link ServletResponse#setCharacterEncoding(String)}.
 * <p>
 * Expose {@link SettingsService} and {@link SecurityUtils} for use in FreeMarker template.
 * <p>
 * Use with {@link FreeMarkerViewResolver}.
 *
 * @author Patrick
 */
public class FreeMarkerView extends org.springframework.web.servlet.view.freemarker.FreeMarkerView {

	private String responseEncoding;

	private SettingsService settingsService;

	/** SecurityUtils for use in FreeMarker template */
	private static final SecurityUtils SECURITY_UTILS = new SecurityUtils();

	public String getResponseEncoding() {
		return responseEncoding;
	}

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

	public SettingsService getSettingsService() {
		return settingsService;
	}

	public void setSettingsService(SettingsService settingsService) {
		this.settingsService = settingsService;
	}

	@Override
	protected void processTemplate(Template template, SimpleHash model, HttpServletResponse response) throws IOException, TemplateException {
		response.setCharacterEncoding(getResponseEncoding());
		super.processTemplate(template, model, response);
	}

	@Override
	protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
		CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
		if (csrf != null)
			model.put("_csrf", csrf.getToken());
		else
			model.put("_csrf", "");
		model.put("SecurityUtils", SECURITY_UTILS);
		model.put("SettingsService", settingsService);
	}

}