package org.nutz.mvc.impl.processor;

import java.lang.reflect.Method;

import org.nutz.ioc.Ioc;
import org.nutz.ioc.Ioc2;
import org.nutz.ioc.IocContext;
import org.nutz.ioc.impl.ComboContext;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.ioc.RequestIocContext;
import org.nutz.mvc.ioc.SessionIocContext;

/**
 * 
 * @author zozoh(zozohtnt@gmail.com)
 * @author wendal(wendal1985@gmail.com)
 * 
 */
public class ModuleProcessor extends AbstractProcessor {

	private String injectName;

	private Class<?> moduleType;
	private Method method;
	private Object moduleObj;

	@Override
	public void init(NutConfig config, ActionInfo ai) throws Throwable {
		method = ai.getMethod();
		moduleType = ai.getModuleType();
		// 不使用 Ioc 容器管理模块
		if (Strings.isBlank(ai.getInjectName())) {
			moduleObj = Mirror.me(moduleType).born();
		}
		// 使用 Ioc 容器管理模块
		else {
			injectName = ai.getInjectName();
		}
	}

	public void process(ActionContext ac) throws Throwable {
		RequestIocContext reqContext = null;
		try {
			if (null != moduleObj) {
				ac.setModule(moduleObj);
			} else {
				Ioc ioc = ac.getIoc();
				if (null == ioc)
					throw Lang.makeThrow(	"Moudle with @InjectName('%s') but you not declare a Ioc for this app",
											injectName);
				Object obj;
				/*
				 * 如果 Ioc 容器实现了高级接口，那么会为当前请求设置上下文对象
				 */
				if (ioc instanceof Ioc2) {
					reqContext = new RequestIocContext(ac.getRequest());
					SessionIocContext sessionContext = new SessionIocContext(ac.getRequest()
																				.getSession());
					IocContext myContext = new ComboContext(reqContext, sessionContext);
					obj = ((Ioc2) ioc).get(moduleType, injectName, myContext);
				}
				/*
				 * 否则，则仅仅简单的从容器获取
				 */
				else
					obj = ioc.get(moduleType, injectName);
				ac.setModule(obj);

			}
			ac.setMethod(method);
			doNext(ac);
		}
		finally {
			if (reqContext != null)
				try {
					reqContext.depose();
				}
				catch (Throwable e) {
					e.printStackTrace();
				}
		}
	}

}

@@ -284,16 +284,69 @@
 rings;%0D%0A
+import org.nutz.log.Log;%0D%0Aimport org.nutz.log.Logs;%0D%0A
 import o
@@ -684,16 +684,64 @@
 essor %7B%0D
+%0A%09%0D%0A%09private static final Log log = Logs.get();%0D
 %0A%0D%0A%09priv
@@ -2132,16 +2132,133 @@
 thod);%0D%0A
+%09%09%09if (log.isDebugEnabled()) //%E6%89%93%E5%8D%B0%E5%AE%9E%E9%99%85%E6%89%A7%E8%A1%8C%E7%9A%84Method%E4%BF%A1%E6%81%AF%0D%0A%09%09%09%09log.debugf(%22Handle URL%5B%25s%5D by Method%5B%25s%5D%22,ac.getPath(),method);%0D%0A
 %09%09%09doNex

add log for mvc : Handle URL by Method