/* ComposerHandler.java

	Purpose:
		
	Description:
		
	History:
		Tue Dec 26 08:48:59 TST 2010, Created by Ashish Dasnurkar

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

*/

package org.zkoss.zss.jsp.ui;

import java.io.Serializable;
import java.util.Collection;

import javax.servlet.jsp.JspException;

import org.zkoss.lang.Classes;
import org.zkoss.util.CollectionsX;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.util.Composer;

/**
 * 
 * @author Ashish
 *
 */
/*package*/ class ComposerHandler implements Serializable{
	private static final long serialVersionUID = -8896072019503986058L;
	
	private Composer composer;
	/**
	 * 
	 * @param apply could be String Collection or a {@link Composer}
	 */
	/*package*/ ComposerHandler(Object apply){
		composer =  parseAppliedComposer( apply);
	}
	private static Composer parseAppliedComposer(Object o) {
		if(null==o)return null;
		try {
			if (o instanceof String) {
				final String s = (String)o;
				if (s.indexOf(',') >= 0)
					o = CollectionsX.parse(null, s, ',');
			}

			if (o instanceof Collection) {
				final Collection c = (Collection)o;
				int sz = c.size();
				switch (sz) {
				case 0: return null;
				case 1: o = c.iterator().next(); break;
				default: o = c.toArray(new Object[sz]); break;
				}
			}

			if (o instanceof Object[]) {
				final Object[] cs = (Object[])o;
				switch (cs.length) {
				case 0: return null;
				case 1: o = cs[0]; break;
				default: return new MultiComposer(cs);
				}
			}

			if (o instanceof String)
				o = Classes.newInstanceByThread(((String)o).trim());
			else if (o instanceof Class)
				o = ((Class)o).newInstance();

			if (o instanceof Composer)
				return (Composer)o;
		} catch (Exception ex) {
			throw UiException.Aide.wrap(ex);
		}
		return null;
	}
	
	/**
	 *  Fire contained {@link Composer}'s  {@link Composer#doAfterCompose(Component)} method.
	 * @param comp the component that should be composed.
	 * @throws JspException if {@link Composer#doAfterCompose(Component)} failed.
	 */
	public void doAfterCompose(Component comp) throws JspException {
		try {
			if(composer!=null)composer.doAfterCompose(comp);
		} catch (Exception e) {
			throw new JspException(e);
		}
	}
}//end of class...
