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

import be.iminds.ilabt.jfed.experimenter_gui.bugreporting.BugReportDialogFactory;
import be.iminds.ilabt.jfed.experimenter_gui.slice.jobs.TestConnectivityJob;
import be.iminds.ilabt.jfed.highlevel.jobs.StateFinishedListener;
import be.iminds.ilabt.jfed.preferences.GuiPreferenceKey;
import be.iminds.ilabt.jfed.preferences.JFedPreferences;
import be.iminds.ilabt.jfed.rspec.model.javafx_impl.FXRspecNode;
import be.iminds.ilabt.jfed.ui.javafx.GlyphUtils;
import javafx.application.HostServices;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.controlsfx.glyphfont.FontAwesome;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Provider;
import java.util.List;
import java.util.stream.Collectors;

/**
 * User: twalcari
 * Date: 12/1/2015
 * Time: 15:38
 */
public class TestConnectivityToExperimentPartsStateListener implements StateFinishedListener<TestConnectivityJob.TestConnectivityToExperimentPartsState> {
    private static final Logger LOG = LoggerFactory.getLogger(TestConnectivityToExperimentPartsStateListener.class);

    private final JFedPreferences jFedPreferences;
    private final Provider<HostServices> hostServicesProvider;
    private final BugReportDialogFactory bugReportDialogFactory;

    public TestConnectivityToExperimentPartsStateListener(JFedPreferences jFedPreferences,
                                                          Provider<HostServices> hostServicesProvider,
                                                          BugReportDialogFactory bugReportDialogFactory) {
        this.jFedPreferences = jFedPreferences;
        this.hostServicesProvider = hostServicesProvider;
        this.bugReportDialogFactory = bugReportDialogFactory;
    }

    @Override
    public void onStateFinished(TestConnectivityJob.TestConnectivityToExperimentPartsState state) {

        List<FXRspecNode> failedNodes = state.getFailedNodes();

        if (!failedNodes.isEmpty()) {
            //show a (mutable) notification to mac-users that the terminal opens in the background
            if (jFedPreferences.getBoolean(GuiPreferenceKey.PREF_SHOW_CONNECTIVITY_WARNING_DIALOG, true)) {
                LOG.debug("Showing connectivity warning dialog");

                VBox pane = new VBox();
                pane.setSpacing(20);

                final Text introText =
                        new Text(String.format("jFed detected that node(s) %s cannot be reached.\n" +
                                        "You can take the following steps to resolve the problem:\n\n",
                                failedNodes.stream().map(FXRspecNode::getClientId).collect(Collectors.joining(", "))));
                introText.setStyle("-fx-font-weight: bold");

                final Hyperlink text1 = new Hyperlink("1. Try enabling the proxy for SSH connections\n");
                text1.setOnAction(actionEvent ->
                        hostServicesProvider.get()
                                .showDocument("http://doc.ilabt.iminds.be/jfed-documentation/advancedfeatures.html#proxy-settings"));

                final Hyperlink text2 = new Hyperlink("2. Check the support forum");
                text2.setOnAction(actionEvent ->
                        hostServicesProvider.get().showDocument("http://doc.fed4fire.eu/support.html"));

                final Hyperlink text3 = new Hyperlink("3. Request assistance by submitting a bug report");
                text3.setOnAction(actionEvent -> bugReportDialogFactory.showDialog());

                TextFlow errorMessageTextFlow = new TextFlow(
                        introText,
                        text1, new Text("\n"),
                        text2, new Text("\n"),
                        text3
                );

                pane.getChildren().add(errorMessageTextFlow);
                final CheckBox checkBox = new CheckBox("Do not show this dialog again");
                pane.getChildren().add(checkBox);

                DialogPane dialogPane = new DialogPane();
                dialogPane.setHeaderText("Experiment connectivity issues");
                dialogPane.setGraphic(GlyphUtils.createDialogGlyph(FontAwesome.Glyph.PLAY, Color.GREEN));
                dialogPane.setContent(pane);
                dialogPane.getButtonTypes().setAll(ButtonType.OK);


                Dialog<ButtonType> dialog = new Dialog<>();
                dialog.setTitle("Experiment connectivity issues");
                dialog.setDialogPane(dialogPane);

                dialog.showAndWait();

                jFedPreferences.setBoolean(GuiPreferenceKey.PREF_SHOW_CONNECTIVITY_WARNING_DIALOG,
                        !checkBox.isSelected());
            } else {
                LOG.debug("Skipping connectivity issues dialog because user muted it before");
            }
        }
    }
}
