package com.airlock.iam.plugin.configeditor.ui.dialog;

import com.vaadin.server.Sizeable.Unit;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class TextAreaDialog extends Window {
   private static final int NR_ROWS = 30;
   private final TextArea textarea;
   private String newValue;

   @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "See ALIAM-15315")
   public TextAreaDialog(String propertyName, String value, boolean readOnly) {
      this.setWidth(800.0F, Unit.PIXELS);
      String readOnlyCaption = readOnly ? " (read only)" : "";
      this.setCaption("Value of " + propertyName + readOnlyCaption);
      this.setModal(true);
      this.setResizable(false);
      this.addStyleName("textAreaDialog");
      VerticalLayout vl = new VerticalLayout();
      HorizontalLayout hl = new HorizontalLayout();
      hl.setWidth("100%");
      this.textarea = new TextArea(propertyName);
      this.textarea.setWordWrap(true);
      this.textarea.setSizeFull();
      this.textarea.setRows(30);
      if (value != null) {
         this.textarea.setValue(value);
      }

      this.textarea.setReadOnly(readOnly);
      vl.addComponent(this.textarea);
      Button saveButton = new Button("Save");
      saveButton.addClickListener(this::saveButtonClick);
      saveButton.addStyleName("primary");
      saveButton.setId("primaryButton");
      saveButton.setEnabled(!readOnly);
      Button cancelButton = new Button("Cancel");
      cancelButton.setId("cancelButton");
      cancelButton.addClickListener(this::cancelButtonClick);
      hl.addComponent(cancelButton);
      hl.addComponent(saveButton);
      hl.setComponentAlignment(saveButton, Alignment.MIDDLE_RIGHT);
      vl.addComponent(hl);
      this.textarea.focus();
      this.setContent(vl);
      UI.getCurrent().addWindow(this);
   }

   public void cancelButtonClick(ClickEvent event) {
      UI.getCurrent().removeWindow(this);
   }

   public void saveButtonClick(ClickEvent event) {
      Object value = this.textarea.getValue();
      this.newValue = value != null ? value.toString() : "";
      UI.getCurrent().removeWindow(this);
   }

   public String getNewValue() {
      return this.newValue;
   }
}
