/* 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.service.comp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Html;
import com.google.gwt.user.client.ui.Widget;

import jp.co.kpscorp.gwt.client.design.WidgetServiceBase;
import jp.co.kpscorp.gwt.client.design.delegate.Delegate;
import jp.co.kpscorp.gwt.client.design.gxt.GxtUtil;

public abstract class WsAdapterBase extends WidgetServiceBase {

	@Override
	public List<String>[] makeSource(List<String>[] lists,
			Map<Object, Object> map) {
		String fn = GxtUtil.getFieldName(lists[0], getFieldString(), getTag());
		lists[0].add(getFieldString() + fn + ";");
		List<String> l = new ArrayList<String>();
		List<String>[] lists2 = new List[2];
		lists2[0] = lists[0];
		lists2[1] = l;
		l.add(fn + getInstanceString());
		Iterator it = getDelegates().iterator();
		while (it.hasNext()) {
			Delegate delegate = (Delegate) it.next();
			delegate.makeSetterCode(widget, lists2, getFieldString(),
					getInstanceString(), getTag(), fn, map);
		}
		GxtUtil.makeAddCode(widget, lists2, map, fn);
		map.put(fn + "_" + getTag(), l);
		return lists;
	}

	@Override
	public Component getInstance(String constracter, Map map) {
		String s = constracter.trim();
		String myS = getInstanceString();
		int mySt = myS.indexOf("new ") + 4;
		int myEd = myS.indexOf('(');
		int st = s.indexOf('(');
		if (!myS.substring(mySt, myEd).equals(s.substring(0, st))) {
			return null;
		}
		int ed = s.indexOf(')');
		Widget w = (Widget) map.get(s.substring(st + 1, ed));
		return getInstance(w);
	}

	public Component getInstance() {
		return getInstance(new Html(GxtUtil.getNewTag(getTag())));
	}

	protected abstract Component getInstance(Widget widget);

}
