/* ActioinBridgeImpl.java

	Purpose:
		
	Description:
		
	History:
		2013/6/27, Dennis

Copyright (C) 2010 Potix Corporation. All Rights Reserved.

*/
package org.zkoss.zss.jsf.ui.impl;

import java.io.Serializable;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.zkoss.lang.Strings;
import org.zkoss.zk.ui.ComponentNotFoundException;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zkplus.embed.Bridge;
import org.zkoss.zss.jsf.Action;
import org.zkoss.zss.jsf.ActionBridge;
import org.zkoss.zssex.ui.impl.BridgeFix;
/**
 * Implement of action bridge
 * @author dennis
 *
 */
public class ActionBridgeImpl implements ActionBridge, Serializable {
	private static final long serialVersionUID = -5308561049234051800L;
	
	String clientId;
	String compUuid;

	public ActionBridgeImpl(String clientId,String compUuid) {
		this.clientId = clientId;
		this.compUuid = compUuid;
	}

	public void execute(Action action) {
		execute(action,false);
	}
	public void execute(Action action,boolean auto) {

		FacesContext context = FacesContext.getCurrentInstance();
		ServletContext svlctx = (ServletContext) context.getExternalContext()
				.getContext();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		HttpServletResponse response = (HttpServletResponse) context
				.getExternalContext().getResponse();

		UIComponent uicomp = FacesUtil.searchComponent(null,clientId);
		
		if(!(uicomp instanceof JSFComponentBase)){
			throw new ComponentNotFoundException("("+clientId+") component is not a zkcomponentbase, is "+uicomp);
		}

		Desktop desktop = ((JSFComponentBase)uicomp).getZKDesktop();
		if(desktop==null){
			if(auto){
				action.execute();
			}else{
				throw new ComponentNotFoundException("can't find any desktop "+((JSFComponentBase)uicomp).getZKDesktopId()+" to excute inside it");
			}
		}else{
			BridgeFix zbridge = new BridgeFix();
			zbridge.start(svlctx, request, response, desktop);
			try {
				action.execute();
				String zkjs = zbridge.getResult();
				if (!Strings.isEmpty(zkjs)) {
					zkjs = getCheckComponentJS(zkjs);
					FacesUtil.addUpdateScript(clientId, zkjs);
				}
			} finally {
				zbridge.close();
			}
		}
	}
	
	private String getCheckComponentJS(String zkjs) {
		StringBuilder sb = new StringBuilder();
		sb.append("if(zssjsf.isDomExist('").append(compUuid).append("')){\n").append(zkjs).append("\n}\n");
		return sb.toString();
	}

}
