package cz.req.ax.builders;

import com.google.common.collect.ImmutableSet;
import com.vaadin.ui.Button;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.UI;
import cz.req.ax.Ax;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Set;

/**
 * @author <a href="mailto:jan.pikl@marbes.cz">Jan Pikl</a>
 *         Date: 15.2.2016
 */
public class AxMessageBuilder {

    private static final Set<String> USER_EXCEPTIONS = ImmutableSet.of("UserException", "ConfigurationException");

    private AxWindowBuilder windowBuilder;
    private LabelBuilder labelBuilder;

    public AxMessageBuilder(String message) {
        labelBuilder = Ax.label(message);
        windowBuilder = Ax.window().style("ax-message").content(labelBuilder.get());
    }

    public AxMessageBuilder error(Throwable throwable) {
        if (USER_EXCEPTIONS.contains(throwable.getClass().getSimpleName())) {
            labelBuilder.value(throwable.getLocalizedMessage());
        }
        Button showButton = windowBuilder.button("Zobrazit výpis chyby").alignLeft().get();
        showButton.addClickListener(event -> {
            showButton.setVisible(false);
            StringWriter writer = new StringWriter();
            throwable.printStackTrace(new PrintWriter(writer));
            TextArea stacktrace = Ax.textArea().value(writer.toString()).rows(20)
                    .wordwrap(false).readOnly().style("stacktrace").get();
            windowBuilder.content(stacktrace).centered();
        });
        return this;
    }

    public AxMessageBuilder html() {
        labelBuilder.html();
        return this;
    }

    public AxMessageBuilder width(int width) {
        windowBuilder.width(width);
        return this;
    }

    public AxMessageBuilder widthUndefined() {
        windowBuilder.widthUndefined();
        return this;
    }

    public void show(UI ui) {
        windowBuilder.show(ui);
    }

    public void show() {
        windowBuilder.show();
    }

}

@@ -972,17 +972,28 @@
        %7D
-%0A
+ else %7B%0A    
         
@@ -1076,32 +1076,36 @@
 .get();%0A        
+   
+ 
 showButton.addCl
@@ -1131,32 +1131,36 @@
 %3E %7B%0A            
+    
 showButton.setVi
@@ -1185,16 +1185,20 @@
         
+  
+  
 StringWr
@@ -1227,24 +1227,28 @@
 ngWriter();%0A
+    
             
@@ -1311,16 +1311,20 @@
         
+    
 TextArea
@@ -1405,16 +1405,20 @@
         
+   
+ 
 .wordwra
@@ -1468,32 +1468,36 @@
 ();%0A            
+    
 windowBuilder.co
@@ -1538,11 +1538,25 @@
     
+ 
-%7D);
+   %7D);%0A        %7D
 %0A   

Fix AxMessageBuilder error