/*
The MIT License

Copyright (c) 2009 Sadiq Jaffer

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

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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

public class TrivialManagerServlet<T> extends HttpServlet
{
	Class<?> mInterface;
	Map<String, Method> mInterfaceMethods;
	T mObject;

	public TrivialManagerServlet(Class<T> pInterface, T pObject)
	{
		mObject = pObject;
		mInterface = pInterface;
		Method[] methods = mInterface.getMethods();
		mInterfaceMethods = new HashMap<String, Method>(methods.length);

		for (int c = 0; c < methods.length; c++)
		{
			Method method = methods[c];

			mInterfaceMethods.put(method.getName(), method);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.println("<html><head><title>Trivial Manager</title></head><body>");

		if (req.getParameter("action") == null)
		{
			for (Method method : mInterfaceMethods.values())
			{
				Class<?> returnType = method.getReturnType();
				Class<?>[] parameterTypes = method.getParameterTypes();

				out.println("<form method=\"get\"><input type=\"hidden\" name=\"action\" value=\"exec\"/>");
				out.println("<input type=\"hidden\" name=\"method\" value=\"" + method.getName() + "\"/>");
				out.println(returnType.getSimpleName() + " <b>" + method.getName() + "</b>(");

				for (int v = 0; v < parameterTypes.length; v++)
				{
					Class<?> parameter = parameterTypes[v];

					out.println(parameter.getSimpleName() + ":<input type=\"text\" name=\"" + v + "\" length=\"10\"/>");
				}

				out.println(")&nbsp;&nbsp;<input type=\"submit\" value=\"Execute\"><br/>");

				out.println("</form><br/><br/>");
			}
		}
		else if (req.getParameter("action").equals("exec"))
		{
			Method method = mInterfaceMethods.get(req.getParameter("method"));

			if (method != null)
			{
				Class<?> returnType = method.getReturnType();
				Class<?>[] parameterTypes = method.getParameterTypes();
				Object[] args = new Object[parameterTypes.length];

				try
				{
					for (int c = 0; c < parameterTypes.length; c++)
					{
						String parameterStr = req.getParameter(Integer.toString(c));

						Class<?> parameter = parameterTypes[c];

						if (parameter == Integer.TYPE)
						{
							args[c] = Integer.parseInt(parameterStr);
						}
						else if (parameter == Double.TYPE)
						{
							args[c] = Double.parseDouble(parameterStr);
						}
						else if (parameter == String.class)
						{
							System.out.println("Adding string..");
							args[c] = parameter.toString();
						}
					}

					try
					{
						Object outObj = method.invoke(mObject, args);

						if (returnType == Collection.class)
						{
							Collection<?> collection = (Collection<?>)outObj;
							
							out.println("<table border=\"1\">");
							
							for( Object obj : collection )
							{
								out.println("<tr><td>" + obj + "</td></tr>");
							}
							
							out.println("</table>");
						}
						else if( returnType == Map.class )
						{
							Map<?,?> map = (Map<?,?>)outObj;
							
							out.println("<table border=\"1\">");
							
							for( Entry<?,?> entry : map.entrySet() )
							{
								out.println("<tr><td>" + entry.getKey() + "</td><td>" + entry.getValue() + "</tr>");
							}
							
							out.println("</table>");							
						}
						else
						{
							out.println("Result: " + outObj);
						}
					}
					catch (InvocationTargetException e)
					{
						Throwable exp = e.getCause();
						out.println("Error: " + exp + "<br/></br><pre>");
						exp.printStackTrace(out);
						out.println("</pre>");

					}
					catch (Exception e)
					{
						out.println("Error: " + e + "<br/></br><pre>");
						e.printStackTrace(out);
						out.println("</pre>");
					}
				}
				catch (NumberFormatException e)
				{
					out.println("Number failed parsing.");
				}
			}
		}

		out.println("</body></html>");
	}
}

