package jp.sourceforge.shovel.struts.pojo.commands;

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

import org.apache.struts.action.ActionMapping;
import org.seasar.framework.beans.BeanDesc;
import org.seasar.framework.beans.PropertyDesc;
import org.seasar.framework.beans.factory.BeanDescFactory;
import org.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
import org.seasar.struts.pojo.PojoCommand;
import org.seasar.struts.pojo.PojoInvocation;
import org.seasar.struts.pojo.util.BindingUtil;
import org.seasar.struts.util.S2StrutsContextUtil;

public class PropertyBindingCommand implements PojoCommand {
    public String execute(PojoInvocation invocation) {
        S2Container container = SingletonS2ContainerFactory.getContainer();
        ActionMapping mapping = invocation.getActionMapping();
        Object action = invocation.getActionInstance();
        
        try {
            invocation.getRequest().setCharacterEncoding("UTF-8");
        } catch(Exception e ) {
        }
        
        BeanDesc beanDesc = BeanDescFactory.getBeanDesc(action.getClass());
        BindingUtil.importProperties(action, container, beanDesc, mapping);
        if (beanDesc.hasPropertyDesc("response")) {
            PropertyDesc propertyDesc = beanDesc.getPropertyDesc("response");
            propertyDesc.setValue(action, invocation.getResponse());
        }
        String forward = invocation.execute();
        HttpServletRequest request = S2StrutsContextUtil.getRequest(container);
        HttpServletResponse response = S2StrutsContextUtil.getResponse(container);
        //Action1 -> Action2 -> View
        //Action2を抜ける間際にexternalContextのrequestとresponseがnullに
        //Action1でのexportPropertiesの必要ない？
        //必要ないけど。。
        if (request != null && response != null) {
            BindingUtil.exportProperties(action, container, beanDesc, mapping);
        }

        return forward;
    }

}
