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

import javafx.fxml.FXMLLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;

/**
 * User: twalcari
 * Date: 5/21/2015
 * Time: 09:00
 */
public class FXMLUtil {
    private static final Logger LOG = LoggerFactory.getLogger(FXMLUtil.class);

    private static final String FXML_SUFFIX = ".fxml";

    private FXMLUtil() {
    }


    public static void injectFXML(Object object) {
        injectFXML(object, null);
    }

    public static void injectFXML(Object object, javafx.util.Callback<java.lang.Class<?>, java.lang.Object> controllerFactory) {
        FXMLLoader fxmlLoader = new FXMLLoader(getFXMLUrl(object));

        fxmlLoader.setRoot(object);
        fxmlLoader.setController(object);

        if (controllerFactory != null) {
            fxmlLoader.setControllerFactory(controllerFactory);
        }

        try {
            fxmlLoader.load();
        } catch (IOException ex) {
            LOG.error("Could not load FXML-file for {}", object.getClass().getName(), ex);
            throw new RuntimeException(ex);
        }
    }

    public static <T> T createFromFXML(Object object) {
        return createFromFXML(object, null);
    }

    public static <T> T createFromFXML(Object object, javafx.util.Callback<java.lang.Class<?>, java.lang.Object> controllerFactory) {
        FXMLLoader fxmlLoader = new FXMLLoader(getFXMLUrl(object));

        fxmlLoader.setController(object);

        if (controllerFactory != null) {
            fxmlLoader.setControllerFactory(controllerFactory);
        }

        try {
            return fxmlLoader.load();
        } catch (IOException ex) {
            LOG.error("Could not load FXML-file for {}", object.getClass().getName(), ex);
            throw new RuntimeException(ex);
        }
    }


    private static URL getFXMLUrl(Object object){
        //we expect the FXML-file to be named exactly like the class-name. ex: ExperimenterGUI.java --> ExperimenterGUI.fxml
        final String fxmlFileName = object.getClass().getSimpleName() + FXML_SUFFIX;
        URL fxmlUrl = object.getClass().getResource(fxmlFileName);

        if (fxmlUrl == null) {
            throw new NullPointerException("Could not resolve fxml-file '" + fxmlFileName + "' for class '" + object.getClass() + "'");
        }

        return fxmlUrl;
    }

}