package ch.openech.mj.edit.fields;

import ch.openech.mj.model.Keys;
import ch.openech.mj.model.PropertyInterface;
import ch.openech.mj.model.Search;
import ch.openech.mj.toolkit.ClientToolkit;
import ch.openech.mj.toolkit.ClientToolkit.ILookup;
import ch.openech.mj.toolkit.ClientToolkit.InputComponentListener;
import ch.openech.mj.toolkit.IComponent;

public class ReferenceField<T> extends AbstractEditField<T> {
	// private static final Logger logger = Logger.getLogger(ReferenceField.class.getName());
	
	private T object;
	protected final ILookup<T> lookup;
	private final Object[] searchColumns;

	public ReferenceField(Object key, Search<T> search) {
		this(key, search, search.getKeys());
	}
	
	public ReferenceField(Object key, Search<T> search, Object... searchColumns) {
		this(key, search, searchColumns, true);
	}

	public ReferenceField(Object key, Search<T> search, Object[] searchColumns, boolean editable) {
		super(key, editable);
		PropertyInterface property = Keys.getProperty(key);
		lookup = ClientToolkit.getToolkit().createLookup(new ReferenceFieldChangeListener(), search, searchColumns);
		this.searchColumns = searchColumns;
	}

	@Override
	public IComponent getComponent() {
		return lookup;
	}

	@Override
	public T getObject() {
		return object;
	}

	@Override
	public void setObject(T object) {
		this.object = object;
		fireObjectChange();
	}
	
	protected void fireObjectChange() {
		display();
		super.fireChange();
	}

	protected void display() {
		if (object != null) {
			lookup.setText(object.toString());
		} else {
			lookup.setText(null);
		}
	}

	private class ReferenceFieldChangeListener implements InputComponentListener {

		@Override
		public void changed(IComponent source) {
			setObject(lookup.getSelectedObject());
		}
		
	}

}

@@ -31,16 +31,62 @@
 lds;%0D%0A%0D%0A
+import ch.openech.mj.edit.value.CloneHelper;%0D%0A
 import c
@@ -194,16 +194,54 @@
 earch;%0D%0A
+import ch.openech.mj.model.ViewUtil;%0D%0A
 import c
@@ -627,79 +627,83 @@
 %0A%09pr
-otected final ILookup%3CT%3E lookup
+ivate final PropertyInterface property
 ;%0D%0A%09pr
-iva
+otec
 te
+d
  final 
-Object%5B%5D searchColumns
+ILookup%3CT%3E lookup
 ;%0D%0A%0D
@@ -1061,34 +1061,16 @@
 le);%0D%0A%09%09
-PropertyInterface 
 property
@@ -1212,47 +1212,8 @@
 );%0D%0A
-%09%09this.searchColumns = searchColumns;%0D%0A
 %09%7D%0D%0A
@@ -1817,26 +1817,40 @@
 ) %7B%0D%0A%09%09%09
-set
+Object selected
 Object
-(
+ = 
 lookup.g
@@ -1867,16 +1867,186 @@
 Object()
+;%0D%0A%09%09%09@SuppressWarnings(%22unchecked%22)%0D%0A%09%09%09T objectAsView = (T) ViewUtil.view(selectedObject, CloneHelper.newInstance(property.getFieldClazz()));%0D%0A%09%09%09setObject(objectAsView
 );%0D%0A%09%09%7D%0D

set view not the complete object as reference