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

import com.airlock.iam.plugin.api.annotation.property.StringProperty;
import com.airlock.iam.plugin.configeditor.data.ConfigurableProperty;
import com.airlock.iam.plugin.configeditor.data.PropertyAdapter;
import com.airlock.iam.plugin.configeditor.ui.dialog.TextAreaDialog;
import com.airlock.iam.plugin.configeditor.util.GuiResources;
import com.vaadin.event.MouseEvents.ClickEvent;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Image;
import com.vaadin.v7.data.Property;
import com.vaadin.v7.data.Property.ValueChangeEvent;
import com.vaadin.v7.ui.AbstractField;
import com.vaadin.v7.ui.TextArea;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class MedusaTextAreaField extends MedusaField<StringProperty, String> {
   private static final String OPEN_DIALOG_ICON_TOOLTIP = "Show value in a separate window.";
   private final Image openDialogIcon = this.makeIcon(GuiResources.ICON_ZOOMIN, "Show value in a separate window.", "with-hand", this);

   @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "See ALIAM-15315")
   public MedusaTextAreaField(PropertyAdapter<StringProperty> propertyAdapter) {
      super(propertyAdapter);
      this.openDialogIcon.addStyleName("lookingGlass");
      this.getFieldLayout().addComponent(this.openDialogIcon);
      this.getFieldLayout().setComponentAlignment(this.openDialogIcon, Alignment.MIDDLE_LEFT);
   }

   @Override
   public AbstractField<String> createInnerField() {
      TextArea field = new TextArea();
      field.setWidth("100%");
      field.setImmediate(true);
      field.setBuffered(false);
      field.setNullRepresentation("");
      field.setRows(7);
      return field;
   }

   public void setPropertyDataSource(Property newDataSource) {
      this.getInnerField().setPropertyDataSource(newDataSource);
      this.updateUiAndValidate();
   }

   public Property<?> getPropertyDataSource() {
      return this.getInnerField().getPropertyDataSource();
   }

   @Override
   public void click(ClickEvent event) {
      super.click(event);
      if (event.getSource() == this.openDialogIcon) {
         this.openDialog();
      }
   }

   @Override
   public void valueChange(ValueChangeEvent event) {
      this.propagateNullValueIfFieldIsUndefined();
      super.valueChange(event);
   }

   private void openDialog() {
      ConfigurableProperty cp = this.getConfigurableProperty();
      TextAreaDialog dialog = new TextAreaDialog(cp.getDisplayName(), this.getValue(), cp.isReadOnly());
      dialog.addCloseListener(e -> {
         if (dialog.getNewValue() != null) {
            this.getInnerField().setValue(dialog.getNewValue());
         }
      });
   }
}
