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

import be.iminds.ilabt.jfed.experimenter_gui.config.JFedGuiConfig;
import be.iminds.ilabt.jfed.experimenter_gui.util.ImageSize;
import be.iminds.ilabt.jfed.experimenter_gui.util.ImageUtil;


import be.iminds.ilabt.jfed.fedmon.webapi.service.json.Server;
import be.iminds.ilabt.jfed.lowlevel.TestbedInfoSource;
import be.iminds.ilabt.jfed.util.GeniUrn;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;

/**
 * User: twalcari
 * Date: 4/24/2015
 * Time: 10:50
 */
public class TestbedAwareCanvasNode extends CanvasNode {

    private final TestbedInfoSource testbedInfoSource;
    private final JFedGuiConfig config;

    protected final ObjectProperty<GeniUrn> componentManagerId = new SimpleObjectProperty<>();

    {
        componentManagerId.addListener(obj -> updateTestbed());
    }

    public TestbedAwareCanvasNode(TestbedInfoSource testbedInfoSource, JFedGuiConfig config) {
        this.testbedInfoSource = testbedInfoSource;
        this.config = config;
    }


    private void updateTestbed() {
        if(componentManagerId.get() != null) {
            Server server =
                    testbedInfoSource.getByUrnExact(componentManagerId.get()); //not ALLOW_TOPLEVEL here!   (purpose would be REQUEST)
            if (server != null) {
                tooltipText.setValue(server.getName());

                Color serverColor = config.getColor(server);
                if (serverColor != null) {
                    color.setValue(serverColor);
                } else {
                    color.setValue(Color.TRANSPARENT);
                }

                Image logoImage = ImageUtil.getTestbedDescriptionImage(server, ImageSize.SMALL); //this might return null
                logo.setValue(logoImage); //this supports null fine
            } else {
                color.setValue(Color.TRANSPARENT);
            }
        }else{
            logo.setValue(null);
            color.setValue(Color.TRANSPARENT);
        }
    }
}
