package be.iminds.ilabt.jfed.ui.javafx.probe_gui.dialog;

import be.iminds.ilabt.jfed.lowlevel.AnyCredential;
import be.iminds.ilabt.jfed.lowlevel.CredentialException;
import be.iminds.ilabt.jfed.util.IOUtils;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.File;
import java.io.IOException;

/**
 * CredentialEditDialog
 */
public class CredentialEditDialog {
    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(CredentialEditDialog.class);

    public static AnyCredential showAddDialog() {
        return showDialog(true, null);
    }
    public static AnyCredential showDialog(final boolean add, final AnyCredential anyCredential) {
        assert add || anyCredential != null;

        final Stage dialog = new Stage();
        dialog.initStyle(StageStyle.UTILITY);
        //        dialog.initModality(Modality.WINDOW_MODAL);
        dialog.initModality(Modality.APPLICATION_MODAL);


        final ObjectProperty<AnyCredential> resultProp = new SimpleObjectProperty<>(null);

        VBox box = new VBox();
        HBox box2 = new HBox();
        HBox.setHgrow(box2, Priority.ALWAYS);
//        box.setAlignment(Pos.CENTER);
        box2.setAlignment(Pos.CENTER);
        Button butOk = new Button("Use this Credential");
        Button butCancel = new Button(add ? "Do not add" : "Cancel Edit");
        Button butLoad = new Button("Load from file...");

        Label internalNameLabel = new Label("Internal Name:");
        final TextField internalNameField = new TextField(anyCredential == null ? "User Imported Credential" : anyCredential.getName());

        Label credentialTypeLabel = new Label("Type:");
        final TextField credentialTypeField = new TextField(anyCredential == null ? /*"geni_sfa"*/"auto" : anyCredential.getType());

        Label credentialVersionLabel = new Label("Version:");
        final TextField credentialVersionField = new TextField(anyCredential == null ? /*"3"*/"auto" : anyCredential.getVersion());

        Label valueLabel = new Label("Xml value:");
        final TextArea valueArea = new TextArea(anyCredential == null ? "" : anyCredential.getCredentialXml());
        valueArea.setEditable(true);
        VBox.setVgrow(valueArea, Priority.ALWAYS);
//        box2.getChildren().add(butLoad);
        box2.getChildren().addAll(butOk, butCancel);
        box.getChildren().addAll(internalNameLabel, internalNameField, credentialTypeLabel, credentialTypeField,
                credentialVersionLabel, credentialVersionField, valueLabel, butLoad, valueArea, box2);

        Scene scene = new Scene(box);
        dialog.setScene(scene);
        dialog.sizeToScene();

        butOk.setOnAction(actionEvent -> {
//                String newName = "User Imported Credential";
//                    if (!add && credentialInfo != null) {
//                        newName = credentialInfo.getCredential().getName();
//                        if (!newName.endsWith(" (Edited)"))
//                            newName += " (Edited)";
//                    }
            String newName = internalNameField.getText();
            AnyCredential resGeniCredential = null;
            try {
                if (valueArea.getText() == null || valueArea.getText().isEmpty() || valueArea.getText().trim().equalsIgnoreCase("auto") ||
                    credentialVersionField.getText() == null || credentialVersionField.getText().isEmpty() || credentialVersionField.getText().trim().equalsIgnoreCase("auto"))
                    resGeniCredential = AnyCredential.createAutoDetect(newName, valueArea.getText());
                else
                    resGeniCredential = AnyCredential.create(newName, valueArea.getText(), credentialTypeField.getText(), credentialVersionField.getText());
                resultProp.set(resGeniCredential);
            } catch (CredentialException e) {
                resultProp.set(null);
                LOG.error("Error creating credential: "+e.getMessage(), e);
            }
            dialog.close();
        });
        butCancel.setOnAction(actionEvent -> {
            resultProp.set(null);
            dialog.close();
        });
        butLoad.setOnAction(actionEvent -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("Open Credential File");
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Credential XML Files", "*.xml"));
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("All Files", "*.*"));
            File file = fileChooser.showOpenDialog(dialog);
            if (file != null) {
                final String content;
                try {
                    content = IOUtils.fileToString(file);
                    Platform.runLater(() -> valueArea.setText(content));
                } catch (IOException e) {
                    LOG.error("Failed to open file: "+file.getPath(), e);
                }
            }
        });

        dialog.showAndWait();

        return resultProp.get();
    }
}
