package com.udapsoft.waf.system.handler;

import java.lang.reflect.Constructor;

import javax.servlet.http.HttpServletRequest;

import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.handler.dao.EventMapping;
import com.udapsoft.waf.system.handler.dao.EventMappingDAO;
import com.udapsoft.waf.system.handler.dao.EventMappings;

public abstract class BizDefaultXmlActionHandler extends
		BizDefaultActionHandler {

	private static final long serialVersionUID = -8605610009132289066L;

	public BizDefaultXmlActionHandler() {
		super();
	}

	protected String doXmlHandle(HttpServletRequest request,
			EventMappings eventMappings) {
		super.doReady(this, request);
		try {
			String screenName = super.getScreenName();
			String event = super.getEvent();
			EventMapping eventMapping = eventMappings.get(screenName, event);

			if (eventMapping != null) {
				for (int i = 0; i < eventMapping.getBizSize(); i++) {
					String bizName = eventMapping.getBiz(i);
					Biz biz = createBiz(bizName);
					biz.doBiz();
				}
			}
		} catch (Exception e) {
			super.doException(e);
		} finally {
			super.doEnd(request);
		}
		return super.screen;
	}

	protected EventMappings loadEventMapping(Class<?> pclass) {
		return EventMappingDAO.loadEventMappings(pclass);
	}

	private Biz createBiz(String bizName) throws Exception {
		Class<?> cls = Class.forName(bizName);
		Class<?>[] argsTypes = new Class[1];
		argsTypes[0] = super.storage.getClass();
		Constructor<?> constructor = cls.getConstructor(argsTypes);
		Object[] args = new Object[1];
		args[0] = super.storage;
		Biz biz = (Biz) constructor.newInstance(args);
		return biz;
	}

	public abstract String doHandle(HttpServletRequest request);
}
