package be.iminds.ilabt.jfed.ui.javafx.scanner;

import be.iminds.ilabt.jfed.fedmon.webapi.service.json.Testbed;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;

/**
 * User: twalcari
 * Date: 12/3/2014
 * Time: 12:06
 */
@Singleton
public class ScanServerDialogFactory {
    private static final Logger LOG = LoggerFactory.getLogger(ScanServerDialogFactory.class);
    private static final String SCAN_AUTHORITY_DIALOG_FXML = "ScanServerDialog.fxml";

    private final FXMLLoader loader;

    @Inject
    ScanServerDialogFactory(FXMLLoader loader) {
        this.loader = loader;
    }

    public static class ScanServerDialogResult {
        private final boolean scanAgain;
        private final Testbed showTestbed;

        public ScanServerDialogResult(boolean scanAgain, Testbed showTestbed) {
            this.scanAgain = scanAgain;
            this.showTestbed = showTestbed;
        }

        public boolean isScanAgain() {
            return scanAgain;
        }

        public Testbed getResult() {
            return showTestbed;
        }
    }

    @Nullable
    public ScanServerDialogResult showScanAuthorityDialog(boolean dialog) {
        Stage stage = new Stage();
        stage.setTitle("Server Scanner");
        if (dialog) {
            stage.initStyle(StageStyle.UTILITY);
            stage.initModality(Modality.APPLICATION_MODAL);
        }

        try {
            loader.setLocation(getClass().getResource(SCAN_AUTHORITY_DIALOG_FXML));

            stage.setScene(new Scene(loader.load()));

            ScanAuthorityDialogController controller = loader.getController();
            controller.setStage(stage);


            stage.sizeToScene();
            stage.showAndWait();

            if (controller.getAMUrl() != null)
                return new ScanServerDialogResult(
                        !controller.isCancelled(),
                        controller.getCreatedTestbed()
                );
            else
                return null;
        } catch (IOException ex) {
            LOG.error("Error while loading ScanAuthorityDialog", ex);
            return null;
        }
    }
}
