package be.iminds.ilabt.jfed.experimenter_gui.slice.ansible;

import be.iminds.ilabt.jfed.rspec.model.AnsibleService;
import be.iminds.ilabt.jfed.rspec.model.javafx_impl.FXRspecNode;
import be.iminds.ilabt.jfed.ui.javafx.GlyphUtils;
import javafx.beans.property.StringProperty;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import org.controlsfx.glyphfont.FontAwesome;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Cedric
 */
public class AnsibleOutputTab extends Tab {
    private static final Logger LOG = LoggerFactory.getLogger(AnsibleOutputTab.class);
    private final FXRspecNode node;
    private final AnsibleService ansibleService;

    private final TabPane content;

    public AnsibleOutputTab(FXRspecNode node, AnsibleService ansibleService,
                            StringProperty galaxyStdOut, StringProperty galaxyStdErr,
                            StringProperty playbookStdOut, StringProperty playbookStdErr) {
        this.node = node;
        this.ansibleService = ansibleService;

        setText(String.format("Ansible playbook '%s'@%s", this.ansibleService.getExecutePlaybook(), this.node.getClientId()));
        final ImageView graphic = new ImageView(getClass().getResource("ansible.png").toExternalForm());
        graphic.setFitHeight(16);
        graphic.setFitWidth(16);
        graphic.setPreserveRatio(true);
        setGraphic(graphic);

        this.content = new TabPane();
        content.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
        content.setSide(Side.LEFT);

        content.getTabs().add(new InputStreamToTextAreaTab(playbookStdOut, GlyphUtils.createGlyph(FontAwesome.Glyph.PLAY), "Playbook Out"));
        content.getTabs().add(new InputStreamToTextAreaTab(playbookStdErr, GlyphUtils.createGlyph(FontAwesome.Glyph.EXCLAMATION_TRIANGLE), "Playbook Err"));
        content.getTabs().add(new InputStreamToTextAreaTab(galaxyStdOut, GlyphUtils.createGlyph(FontAwesome.Glyph.DOWNLOAD), "Galaxy Out"));
        content.getTabs().add(new InputStreamToTextAreaTab(galaxyStdErr, GlyphUtils.createGlyph(FontAwesome.Glyph.EXCLAMATION_CIRCLE), "Galaxy Err"));

        setContent(content);

    }

    private static class InputStreamToTextAreaTab extends Tab {

        private final TextArea textArea;


        private InputStreamToTextAreaTab(StringProperty content, Node graphic, String text) {
            setGraphic(graphic);
            setText(text);

            this.textArea = new TextArea();
            textArea.setWrapText(true);
            textArea.setEditable(false);
            setContent(textArea);
            textArea.textProperty().bind(content);

            textArea.textProperty().addListener(observable -> textArea.setScrollTop(Double.MAX_VALUE));
        }

    }


}
