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

import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
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 CleanUpUnconnectedPluginsDialog extends Window {
   private Button deleteButton;
   private Button cancelButton;
   private boolean deleteRequested = false;

   @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "See ALIAM-15315")
   public CleanUpUnconnectedPluginsDialog() {
      this.setProperties();
      this.createButtons();
      VerticalLayout vl = new VerticalLayout();
      vl.addComponent(this.makeDescriptionLabel());
      HorizontalLayout hl = new HorizontalLayout();
      hl.setWidth(100.0F, Unit.PERCENTAGE);
      hl.addComponent(this.cancelButton);
      hl.addComponent(this.deleteButton);
      hl.setComponentAlignment(this.deleteButton, Alignment.MIDDLE_RIGHT);
      vl.addComponent(hl);
      this.deleteButton.focus();
      this.setContent(vl);
      UI.getCurrent().addWindow(this);
   }

   private void setProperties() {
      this.setWidth(300.0F, Unit.PIXELS);
      this.setCaption("Delete all unconnected plugins");
      this.setModal(true);
      this.setResizable(false);
   }

   private void createButtons() {
      this.deleteButton = new Button("Delete");
      this.deleteButton.setId("primaryButton");
      this.deleteButton.addClickListener(this::deleteButtonClick);
      this.deleteButton.setClickShortcut(13, new int[0]);
      this.deleteButton.addStyleName("button-delete");
      this.cancelButton = new Button("Cancel");
      this.cancelButton.setId("cancelButton");
      this.cancelButton.addClickListener(this::cancelButtonClick);
      this.cancelButton.setClickShortcut(27, new int[0]);
   }

   private Label makeDescriptionLabel() {
      Label descriptionLabel = new Label();
      descriptionLabel.setWidth(100.0F, Unit.PERCENTAGE);
      descriptionLabel.setContentMode(ContentMode.HTML);
      descriptionLabel.setValue(
         "Delete all will first disconnect all plugins attached to the root plugins displayed in the <i>Unconnected Plugins</i> tree. Afterwards, the root plugins and their children (inheritance) are deleted."
      );
      return descriptionLabel;
   }

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

   public void deleteButtonClick(ClickEvent event) {
      this.deleteRequested = true;
      UI.getCurrent().removeWindow(this);
   }

   public boolean isDeleteRequested() {
      return this.deleteRequested;
   }
}
