package org.minimalj.frontend.form.element;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.Frontend.Input;
import org.minimalj.frontend.Frontend.SwitchComponent;
import org.minimalj.model.Selection;
import org.minimalj.util.IdUtils;

public class SelectionFormElement<T> extends AbstractFormElement<Selection<T>> {

	private final SwitchComponent component;
	private Input<T> input;

	public SelectionFormElement(Object key) {
		super(key);
		component = Frontend.getInstance().createSwitchComponent();
	}

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

	@Override
	public void setValue(Selection<T> selection) {
		List<T> values = selection != null && selection.values != null ? selection.values : Collections.emptyList();
		component.show(input = Frontend.getInstance().createComboBox(values, listener()));
		T selectedValue = selection != null ? selection.selectedValue : null;
		if (selectedValue != null && !values.contains(selectedValue) && IdUtils.hasId(selectedValue.getClass())) {
			Object id = IdUtils.getId(selectedValue);
			selectedValue = values.stream().filter(c -> Objects.equals(id, IdUtils.getId(c))).findFirst().orElse(null);
			input.setValue(selectedValue);
			fireChange();
		} else {
			input.setValue(selectedValue);
		}
	}

	@Override
	public Selection<T> getValue() {
		return new Selection<T>(input.getValue());
	}
}

@@ -818,45 +818,53 @@
 %0D%0A%09%09
-List%3CT%3E values = selection != null &&
+if (selection != null) %7B%0D%0A%09%09%09List%3CT%3E values =
  sel
@@ -928,24 +928,25 @@
 ptyList();%0D%0A
+%09
 %09%09component.
@@ -1019,16 +1019,17 @@
 r()));%0D%0A
+%09
 %09%09T sele
@@ -1043,28 +1043,8 @@
 ue =
- selection != null ?
  sel
@@ -1067,20 +1067,14 @@
 alue
- : null
 ;%0D%0A%09%09
+%09
 if (
@@ -1177,16 +1177,17 @@
 ())) %7B%0D%0A
+%09
 %09%09%09Objec
@@ -1227,16 +1227,17 @@
 e);%0D%0A%09%09%09
+%09
 selected
@@ -1321,16 +1321,24 @@
 dFirst()
+%0D%0A%09%09%09%09%09%09
 .orElse(
@@ -1345,16 +1345,17 @@
 null);%0D%0A
+%09
 %09%09%09input
@@ -1384,16 +1384,17 @@
 e);%0D%0A%09%09%09
+%09
 fireChan
@@ -1400,16 +1400,17 @@
 nge();%0D%0A
+%09
 %09%09%7D else
@@ -1416,16 +1416,17 @@
 e %7B%0D%0A%09%09%09
+%09
 input.se
@@ -1449,16 +1449,179 @@
 alue);%0D%0A
+%09%09%09%7D%0D%0A%09%09%7D else %7B%0D%0A%09%09%09input = Frontend.getInstance().createComboBox(Collections.emptyList(), listener());%0D%0A%09%09%09input.setEditable(false);%0D%0A%09%09%09component.show(input);%0D%0A
 %09%09%7D%0D%0A%09%7D%0D

Disable for null selection