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.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.net.URL;

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

    private final FXMLLoader loader;

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


    /**
     * @param testbed
     * @param dialog
     * @return scanAgain
     */
    public boolean showScanResultPanel(Testbed testbed, boolean dialog) {
        Stage stage = new Stage();
        stage.setTitle("Server Scan Result");
        if (dialog) {
            stage.initStyle(StageStyle.UTILITY);
            stage.initModality(Modality.APPLICATION_MODAL);
        }

        try {
            URL location = getClass().getResource(SCAN_RESULT_PANEL_FXML);
            loader.setLocation(location);
            stage.setScene(new Scene(loader.load()));

            ScanResultPanelController controller = loader.getController();
            controller.setTestbed(testbed);
            controller.setStage(stage);

            stage.sizeToScene();
            LOG.debug("Showing scanner panel");
            controller.showJsonSnippet();
            stage.showAndWait();
            return controller.isScanAgain();
        } catch (IOException ex) {
            LOG.error("Error while loading ScanResultPanel", ex);
            return false;
        }
    }
}
