package be.iminds.ilabt.jfed.experimenter_gui.ui;

import be.iminds.ilabt.jfed.ui.javafx.util.StageUtils;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Provider;
import java.io.IOException;
import java.net.URL;

/**
 * User: twalcari
 * Date: 12/16/2014
 * Time: 10:41
 */
public abstract class AbstractDialogFactory {
    private static final Logger LOG = LoggerFactory.getLogger(AbstractDialogFactory.class);
    private static final String FACTORY_SUFFIX = "Factory";

    private final Provider<FXMLLoader> loaderProvider;
    private final Provider<? extends Window> ownerWindowProvider;

    public AbstractDialogFactory(Provider<FXMLLoader> loaderProvider, Provider<? extends Window> ownerWindowProvider) {
        this.loaderProvider = loaderProvider;
        this.ownerWindowProvider = ownerWindowProvider;
    }

    protected URL getFxmlLocation() {

        if (!getClass().getSimpleName().endsWith(FACTORY_SUFFIX))
            throw new RuntimeException("Automatic detection of FXML location can only happen when class ends on '" + FACTORY_SUFFIX + "'");

        String locationString = getClass().getSimpleName();
        locationString = locationString.substring(0, locationString.length() - FACTORY_SUFFIX.length());
        locationString += ".fxml";

        return getClass().getResource(locationString);

    }

    protected abstract String getTitle();

    protected Image[] getIcons() {
        return new Image[]{
                new Image(AbstractDialogFactory.class.getResource("/images/jfed-logo_16.png").toExternalForm())
                , new Image(AbstractDialogFactory.class.getResource("/images/jfed-logo_32.png").toExternalForm())
                , new Image(AbstractDialogFactory.class.getResource("/images/jfed-logo_64.png").toExternalForm())};
    }

    public void showDialog() {
        FXMLLoader loader = loaderProvider.get();
        try {
            loader.setLocation(getFxmlLocation());

            Stage stage = new Stage();
            StageUtils.setJFedStageIcons(stage);
            stage.initOwner(ownerWindowProvider.get());
            stage.setTitle(getTitle());
            stage.getIcons().addAll(getIcons());

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

            Object controller = loader.getController();
            if (controller instanceof SceneAwareController) {
                ((SceneAwareController) controller).registerScene(scene);
            }

            stage.showAndWait();

        } catch (IOException e) {
            LOG.error("Could not show '" + getTitle() + "' dialog", e);
            throw new RuntimeException("Something went wrong showing the " + getTitle() + " dialog: " + e.getMessage(), e);
        }
    }
}
