package tvark.jsf;

import java.io.IOException;

import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

public class CopyComponent extends UIComponentBase implements StateHolder {
	
	public static final String COMPONENT_TYPE = "tvark.Copy";
	
	public static final String COMPONENT_FAMILY = "tvark.Copy";

	private ValueExpression mSource;
	
	private ValueExpression mTarget;
	
	
	@Override
	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	@Override
	public void restoreState(FacesContext pCtx, Object pState) {
		Object[] state = (Object[]) pState;
		Object parent = state[0];
		super.restoreState(pCtx, parent);
		mSource = (ValueExpression) state[1];
		mTarget = (ValueExpression) state[2];
	}

	@Override
	public Object saveState(FacesContext pCtx) {
		Object parent = super.saveState(pCtx);
		Object[] state = {parent, mSource, mTarget};
		return state;
	}

	@Override
	public void decode(FacesContext pCtx) {
		super.decode(pCtx);
		execute(pCtx);
	}

	@Override
	public void encodeBegin(FacesContext pCtx) throws IOException {
		super.encodeBegin(pCtx);
		execute(pCtx);		
	}
	
	private void execute(FacesContext pCtx) {
		ELContext elctx = pCtx.getELContext();
		mTarget.setValue(elctx, mSource.getValue(elctx));	
	}

	public ValueExpression getSource() {
		return mSource;
	}

	public void setSource(ValueExpression pSource) {
		mSource = pSource;
	}

	public ValueExpression getTarget() {
		return mTarget;
	}

	public void setTarget(ValueExpression pTarget) {
		mTarget = pTarget;
	}
	
	

}
