package org.theonefx.wcframework.mvc.wcweb;
import org.theonefx.wcframework.mvc.wcweb.view.IdentifyingCodeView;
import org.theonefx.wcframework.mvc.wcweb.view.JSONView;
import org.theonefx.wcframework.mvc.wcweb.view.StringBodyView;
public class DefaultActionInvocation implements ActionInvocation {
private final ActionInvoker action;
private final ActionInvocationContext context;
private FilterChain filterChain = null;
private int index = -1;
public View[] getCurrentViews() {
if (filterChain == null || index >= filterChain.getSize()) {
return action.getViews();
} else {
return filterChain.get(index).getViews();
}
}
public ActionInvoker getActionInvoker() {
return action;
}
public ActionInvocationContext getActionContext() {
return context;
}
public DefaultActionInvocation(ActionInvoker action, FilterChain filterChain, ActionInvocationContext context) {
this.action = action;
this.filterChain = filterChain;
this.context = context;
}
public DefaultActionInvocation(ActionInvoker invoker, ActionInvocationContext context) {
this.action = invoker;
this.context = context;
}
@Override
public Object process() throws Exception {
index++;
if (filterChain == null || index >= filterChain.getSize()) {
try {
return invokeActionOnly();
} catch (Exception e) {
index--;
throw e;
}
}
FilterInvoker filter = filterChain.get(index);
if (filter != null) {
try {
return filter.invoke(this);
} catch (Exception e) {
index--;
throw e;
}
} else {
return process();
}
}
@Override
public Action getAction() {
return action;
}
@Override
public Object invokeActionOnly() throws Exception {
Object result = action.execute(context);
if (action.getBodyType() != null && (result == null || (result != null && !(result instanceof View)))) {
Object view = null;
switch (action.getBodyType()) {
case STRING:
StringBodyView stringBodyView = new StringBodyView();
stringBodyView.setArgs(result);
view = stringBodyView;
break;
case JSON:
JSONView jsonView = new JSONView();
jsonView.setArgs(result);
view = jsonView;
break;
case IDENTIFYINGCODE:
IdentifyingCodeView identifyCodeView = new IdentifyingCodeView();
identifyCodeView.setArgs(result);
view = identifyCodeView;
}
result = view;
}
return result;
}
}