/*
 * Copyright (c) 2018 無色眼镜
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package club.dawdler.clientplug.web.plugs.impl;

import java.io.PrintWriter;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.clientplug.web.annotation.RequestMapping.ViewType;
import club.dawdler.clientplug.web.handler.ViewForward;
import club.dawdler.clientplug.web.handler.ViewForward.ResponseType;
import club.dawdler.clientplug.web.plugs.AbstractDisplayPlug;
import club.dawdler.util.JsonProcessUtil;
import club.dawdler.util.spring.MediaType;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author jackson.song
 * @version V1.0
 * json的实现
 */
public class JsonDisplayPlug extends AbstractDisplayPlug {
	private static final Logger logger = LoggerFactory.getLogger(JsonDisplayPlug.class);

	@Override
	public void display(ViewForward wf) {
		logException(wf);
		HttpServletRequest request = wf.getRequest();
		HttpServletResponse response = wf.getResponse();
		if (response.getContentType() == null) {
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		}
		String json = null;
		if (wf.getInvokeException() != null) {
			wf.setStatus(ResponseType.ERROR);
		}
		switch (wf.getStatus()) {
		case SUCCESS: {
			if (wf.isAddRequestAttribute()) {
				Enumeration<String> attrs = request.getAttributeNames();
				while (attrs.hasMoreElements()) {
					String key = attrs.nextElement();
					Object obj = request.getAttribute(key);
					wf.putData(key, obj);
				}
			}
			if (wf.getData() != null) {
				if (wf.isJsonIgnoreNull()) {
					json = JsonProcessUtil.ignoreNullBeanToJson(wf.getData());
				} else {
					json = JsonProcessUtil.beanToJson(wf.getData());
				}
			}
			break;
		}
		case ERROR: {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			wf.putData("msg", "Internal Server Error!");
			json = JsonProcessUtil.beanToJson(wf.getData());
			break;
		}
		case REDIRECT:
		case FORWARD:
		case STOP:
			return;
		}
		if (json != null) {
			print(response, json);
		}
	}

	private void print(HttpServletResponse response, String message) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(message);
			out.flush();
		} catch (Exception e) {
			logger.error("Failed to write json response body, the client may receive an incomplete response.", e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@Override
	public void init(ServletContext servletContext) {

	}

	@Override
	public String plugName() {
		return ViewType.json.toString();
	}

}
