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

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.plugs.AbstractDisplayPlug;
import club.dawdler.util.spring.MediaType;

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

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

	@Override
	public void display(ViewForward wf) {
		logException(wf);
		HttpServletRequest request = wf.getRequest();
		HttpServletResponse response = wf.getResponse();
		if (response.getContentType() == null) {
			response.setContentType(MediaType.TEXT_HTML_UTF8_VALUE);
		}
		if (wf.getInvokeException() != null) {
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!");
			} catch (IOException e) {
				logger.error("Failed to send 500 internal server error response for {}.", request.getRequestURI(), e);
			}
			return;
		}
		String tPath = null;
		switch (wf.getStatus()) {
			case SUCCESS:
				tPath = wf.getTemplatePath();
				break;
			case ERROR:
				tPath = wf.getErrorPage();
				break;
			case REDIRECT:
				tPath = wf.getForwardAndRedirectPath();
				try {
					response.sendRedirect(tPath);
				} catch (IOException e) {
					logger.error("Failed to redirect to {}.", tPath, e);
				}
				return;
			case FORWARD:
				tPath = wf.getForwardAndRedirectPath();
				try {
					request.getRequestDispatcher(tPath).forward(request, response);
				} catch (ServletException | IOException e) {
					logger.error("Failed to forward to {}.", tPath, e);
				}
				return;
			case STOP:
				return;
		}
		try {
			Map<String, Object> data = wf.getData();
			if (data != null) {
				Set<Entry<String, Object>> entries = data.entrySet();
				for (Entry<String, Object> entry : entries) {
					request.setAttribute(entry.getKey(), entry.getValue());
				}
			}
			request.getRequestDispatcher(path + tPath).forward(request, response);
		} catch (ServletException | IOException e) {
			logger.error("Failed to render jsp {}{}.", path, tPath, e);
		}
	}

	@Override
	public void init(ServletContext servletContext) {
		String templatePath = servletContext.getInitParameter("template-path");
		if (templatePath != null && !templatePath.trim().equals("")) {
			path = "/WEB-INF/" + templatePath + "/";
		} else {
			path = "/WEB-INF/template/";
		}

	}

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