package com.airlock.iam.plugin.configeditor.field;

import com.airlock.iam.plugin.configeditor.data.ConfigurableProperty;
import com.vaadin.v7.data.Item;
import com.vaadin.v7.data.Property;
import com.vaadin.v7.ui.ComboBox;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;

class NonEmptyDefaultValueToNullSelectionItemCombobox extends ComboBox {
   public Item addItem(Object itemId) throws UnsupportedOperationException {
      return itemId instanceof String ? this.addItemIfNotBlank((String)itemId) : super.addItem(itemId);
   }

   private Item addItemIfNotBlank(String itemId) {
      String newItemId = itemId.trim();
      return StringUtils.isNotBlank(newItemId) ? super.addItem(newItemId) : null;
   }

   public void setPropertyDataSource(Property newDataSource) {
      Optional<Property<?>> adapter = ValueMapperPropertyAdapter.fromPropertyDataSource(newDataSource, this::defaultValueToNullMapper);
      super.setPropertyDataSource(adapter.orElse(newDataSource));
   }

   private Object defaultValueToNullMapper(ConfigurableProperty configurableProperty) {
      return configurableProperty.isValueFromDefault() ? null : configurableProperty.getValue();
   }
}
