/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fitbank.servlet;

import java.lang.reflect.Method;
import java.util.Enumeration;

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

import com.fitbank.common.logger.FitbankLogger;
import com.fitbank.web.DataManage;

public class ManagerServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public static final String KEY = "dm";

	@SuppressWarnings("unused")
	private ServletConfig servletConfig;

	private Method getMethod(String action) throws Exception {
		Method method[] = DataManage.class.getMethods();
		for (Method m : method) {
			if (m.getName().compareTo(action) == 0) {
				if ((m.getParameterTypes() == null) || (m.getParameterTypes().length == 0)) {
					return m;
				}
			}
		}
		throw new Exception("No se ha encontrado el m�todo " + action);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		this.servletConfig = config;
		super.init(config);
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void service(HttpServletRequest req, HttpServletResponse resp) {
		String location = null;
		try {
			location = req.getParameter("location");
			DataManage dm = (DataManage) req.getSession().getAttribute(KEY);
			if (dm == null) {
				dm = new DataManage();
			}
			dm.setRequest(req);
			dm.setHttpSession(req.getSession());
			String action = req.getParameter("operation");
			Method method = this.getMethod(action);
			String answer = (String) method.invoke(dm, null);
			req.getSession().setAttribute(KEY, dm);
			Enumeration<String> en = req.getParameterNames();
			String param = "";
			boolean first = true;
			while (en.hasMoreElements()) {
				String p = en.nextElement();
				if (p.indexOf("dm.") == 0) {
					FitbankLogger.getLogger().debug("Bind>>>>" + p + "=" + req.getParameter(p));
					continue;
				}
				String add = "";
				if (first) {
					first = false;
				} else {
					add = "&";
				}
				param += add + p + "=" + req.getParameter(p);
			}

			if (answer.compareTo("") == 0) {
				location += ((location.indexOf("?") > -1) ? "&" : "?") + param;
				resp.sendRedirect(location);
			} else {
				answer += ((answer.indexOf("?") > -1) ? "&" : "?") + param;
				resp.sendRedirect(answer);
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				req.getRequestDispatcher(location).forward(req, resp);
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}

	}

}
