package be.iminds.ilabt.jfed.experimenter_gui.editor.rspec_validation;

import be.iminds.ilabt.jfed.rspec.model.ModelRspecType;
import be.iminds.ilabt.jfed.rspec.model.impl.BasicDistributeSshKeypair;
import be.iminds.ilabt.jfed.rspec.model.javafx_impl.FXModelRspec;
import be.iminds.ilabt.jfed.rspec.rspec_source.RequestRspecSource;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.stage.Window;

import java.util.Optional;

/**
 * User: twalcari
 * Date: 11/8/2016
 * Time: 12:03
 */
public class AnsibleServiceValidator implements RspecValidator {
    @Override
    public RspecValidationResult validateRSpec(RspecCheckReason reason, RequestRspecSource requestRspecSource, Window dialogOwner) {
        final FXModelRspec modelRspec = requestRspecSource.getModelRspec(ModelRspecType.FX);
        if (modelRspec.getNodes().stream().anyMatch(node -> !node.getAnsibleServices().isEmpty())
                && modelRspec.getDistributeSshKeypairs().isEmpty()) {

            Alert dialog = new Alert(Alert.AlertType.WARNING);
            dialog.initOwner(dialogOwner);
            dialog.setTitle("Ansible services defined without distributed SSH Keys");
            dialog.setHeaderText("No distributed SSH Keys defined");
            dialog.setContentText("The RSpec contains an Ansible Service, but no distributed SSH keys. The latter is needed to allow the Ansible-node to connect to the other nodes in the experiment. Do you want to add a distributed SSH Keypair?");

            ButtonType addKeypairButtonType = new ButtonType("Add keypair", ButtonBar.ButtonData.YES);
            ButtonType ignoreButtonType = new ButtonType("Ignore", ButtonBar.ButtonData.NO);

            dialog.getButtonTypes().setAll(addKeypairButtonType, ignoreButtonType, ButtonType.CANCEL);

            final Optional<ButtonType> result = dialog.showAndWait();

            if (!result.isPresent() || result.get() == ButtonType.CANCEL) {
                return new RspecValidationResult(requestRspecSource, true);
            } else if (result.get() == addKeypairButtonType) {
                modelRspec.addDistributeSshKeypair(new BasicDistributeSshKeypair(null, null));
                return new RspecValidationResult(modelRspec);
            } else {
                return new RspecValidationResult(requestRspecSource, false);
            }
        } else {
            return null;
        }

    }
}
