/*******************************************************************************
 * 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.json;

import java.util.Map;

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

import org.springframework.web.servlet.View;

import com.ffii.core.utils.JsonUtils;
import com.ffii.core.utils.StringUtils;
import com.ffii.core.utils.web.ServletResponseUtils;
import com.ffii.core.web.view.AbstractView;

/**
 * {@link View} implementation to render the specified view data model as a JSON response.
 *
 * @see View
 * @author Patrick
 */
public class JsonView extends AbstractView {

	/**
	 * Default view name of JsonView bean
	 */
	public static final String NAME = "jsonView";

	@Override
	protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
		// set response content type and encoding
		if (StringUtils.contains(request.getHeader("Content-Type"), "multipart/form-data"))
			response.setContentType(CONTENT_TYPE_TEXT_HTML);
		else
			response.setContentType(CONTENT_TYPE_JSON);
		response.setCharacterEncoding(CHARSET_UTF8);
		if (disableCaching) {
			ServletResponseUtils.disableCaching(response);
		}
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// create json string from model
		String jsonString = JsonUtils.toJsonString(model);

		// encode json string and write to stream
		ServletResponseUtils.writeStringToStream(response, CHARSET_UTF8, jsonString);
	}

}
