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

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.zip.GZIPOutputStream;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.clientplug.velocity.resource.loader.DawdlerVelocityResourceLoader;
import club.dawdler.clientplug.velocity.template.manager.VelocityTemplateManager;
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.PropertiesUtil;
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
 * velocity的实现
 */
public class VelocityDisplayPlug extends AbstractDisplayPlug {
	private static final Logger logger = LoggerFactory.getLogger(VelocityDisplayPlug.class);
	private Map<String, VelocityToolBox> toolBoxes = new HashMap<>();

	public Map<String, VelocityToolBox> getToolBoxes() {
		return toolBoxes;
	}

	public void setToolBoxes(Map<String, VelocityToolBox> toolBoxes) {
		this.toolBoxes = toolBoxes;
	}

	@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 error response to client.", 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);
			}
			return;
		case FORWARD:
			tPath = wf.getForwardAndRedirectPath();
			try {
				request.getRequestDispatcher(tPath).forward(request, response);
			} catch (ServletException | IOException e) {
				logger.error("Failed to forward to {}.", tPath);
			}
			return;
		case STOP:
			return;
		default:
			break;
		}
		try {
			mergeTemplate(request, response, tPath, wf);
		} catch (Exception e) {
			logger.error("Failed to render velocity template {}.", tPath);
			return;
		}
	}

	private void mergeTemplate(HttpServletRequest request, HttpServletResponse response, String tPath, ViewForward wf)
			throws IOException, ServletException {
		if (tPath == null) {
			throw new ServletException("not set template!");
		}
		PrintWriter out = null;
		try {
			Template template = VelocityTemplateManager.getInstance().getTemplate(tPath);
			Map<String, Object> data = wf.getData();
			Context context = new VelocityContext(data);
			if (wf.isAddRequestAttribute()) {
				Enumeration<String> attrs = request.getAttributeNames();
				while (attrs.hasMoreElements()) {
					String key = attrs.nextElement();
					Object obj = request.getAttribute(key);
					context.put(key, obj);
				}
			}
			if (!toolBoxes.isEmpty()) {
				Set<Entry<String, VelocityToolBox>> vts = toolBoxes.entrySet();
				for (Entry<String, VelocityToolBox> en : vts) {
					context.put(en.getKey(), en.getValue());
				}
			}
			String ae = request.getHeader("accept-encoding");
			if (ae != null && ae.indexOf("gzip") != -1) {
				out = new PrintWriter(new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()),
						StandardCharsets.UTF_8));
				response.setHeader("Content-Encoding", "gzip");
			} else {
				out = response.getWriter();
			}
			template.merge(context, out);
			out.flush();
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@Override
	public void init(ServletContext servletContext) {
		Properties psTool = null;
		try {
			psTool = PropertiesUtil.loadActiveProfileIfNotExistUseDefaultProperties("toolBoxes");
		} catch (Exception e) {
			logger.error("Failed to load toolBoxes properties, velocity plug initialization is aborted.", e);
			return;
		}
		Set<Object> set = psTool.keySet();
		for (Object o : set) {
			String name = o.toString();
			String className = psTool.get(name).toString();
			try {
				Class<?> c = Class.forName(className);
				if (!VelocityToolBox.class.isAssignableFrom(c)) {
					logger.error("Tool box class {} must extend VelocityToolBox, it will be skipped.", className);
					continue;
				}
				Constructor<?> cs = c.getConstructor(String.class);
				VelocityToolBox obj = (VelocityToolBox) cs.newInstance(name);
				toolBoxes.put(name, obj);
			} catch (Exception e) {
				logger.error("Failed to create velocity tool box {} (class {}), it will be skipped.", name, className);
			}
		}
		VelocityTemplateManager tm = VelocityTemplateManager.getInstance();

		Properties ps = null;
		try {
			ps = PropertiesUtil.loadProperties("velocity");
		} catch (Exception e) {
			ps = new Properties();
		}
		ps.setProperty(RuntimeConstants.RESOURCE_LOADERS, "class");
		ps.setProperty("resource.loader.class.class", DawdlerVelocityResourceLoader.class.getName());
		tm.init(ps);

	}

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