/* D-RexGxt - D-RexGxt - GUI Design Tool for GWT
 * Copyright (c) 2008,  KPS Corporation
 * All rights reserved.
 *
 * Open Source License
 * ------------------------------------------------------------------------------------------
 * D-RexGxt is licensed under the terms of the Open Source GPL 3.0 license.
 *
 * http://www.gnu.org/licenses/gpl.html
 *
 * --
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */
package jp.co.kpscorp.gwt.client.design.gxt.delegate.layout;

import java.util.List;

import jp.co.kpscorp.gwt.client.design.WidgetService;
import jp.co.kpscorp.gwt.client.design.gxt.GxtUtil;
import jp.co.kpscorp.gwt.client.design.gxt.widget.RowLayoutWidget;

import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ComponentHelper;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.LayoutData;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;

public class RowLayoutDelegate extends LayoutDelegate {

	private RowLayoutWidget comp;

	protected String[] props = { "orientation" };

	public RowLayoutDelegate(WidgetService service, Component widget) {
		super(service, widget);
		this.comp = (RowLayoutWidget) widget;
	}

	@Override
	public Object exec(String mthodName, Object[] parms) {
		if ("getOrientation".equals(mthodName)) {
			return comp.getOrientation();
		} else if ("setOrientation".equals(mthodName)
				&& parms[0] instanceof Orientation) {
			comp.setOrientation((Orientation) parms[0]);
			return comp;
		}
		return super.exec(mthodName, parms);
	}

	@Override
	public String[] getProps() {
		return GxtUtil.add(super.getProps(), props);
	}

	@Override
	public LayoutData getValidLayoutData() {
		return new RowData();
	}

	@Override
	public void resetLayoutWhenAdd(Component addComp) {
		if (!(ComponentHelper.getLayoutData(addComp) instanceof RowData)) {
			setRowWidth(comp.getContainer());
		}
	}

	public static void setRowWidth(LayoutContainer container) {
		if (!(container.getLayout() instanceof RowLayout)) {
			return;
		}
		List l = container.getItems();
		if (l.size() > 0) {
			int wt = 100 / l.size();
			double d = ((double) wt) / 100;
			for (int i = 0; i < l.size(); i++) {
				Component c = (Component) l.get(i);
				RowData cd = new RowData(1, d);
				ComponentHelper.setLayoutData(c, cd);
			}
		}

	}

}
