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

import be.iminds.ilabt.jfed.experimenter_gui.canvas.NewLinkTarget;
import be.iminds.ilabt.jfed.gts.model.impl.FXGtsLink;
import be.iminds.ilabt.jfed.gts.model.impl.FXGtsPort;
import be.iminds.ilabt.jfed.gts.model.impl.FXGtsType;
import javafx.beans.InvalidationListener;
import javafx.scene.control.Button;

/**
 * User: twalcari
 * Date: 2/10/2016
 * Time: 17:10
 */
public class GtsCanvasLink extends Button {

    private static final String LINK_CENTER_STYLECLASS = "link-center";
    private final FXGtsLink link;
    private final GtsTypeToCanvasBinding binding;

    private final InvalidationListener updatePositionListener = observable -> updatePosition();

    public GtsCanvasLink(FXGtsLink link, GtsTypeToCanvasBinding binding) {
        this.link = link;
        this.binding = binding;

        textProperty().bind(link.idProperty());

        getStyleClass().add(LINK_CENTER_STYLECLASS);


        this.widthProperty().addListener(observable -> updatePosition());
        this.heightProperty().addListener(observable -> updatePosition());
    }

    void updatePosition() {
        double centerX = 0;
        double centerY = 0;

        int count = 0;
        for (FXGtsPort linkPort : link.getPorts().values()) {
            FXGtsType.NodeToLinkAdjacencyInfo ntlAdjInfo =
                    (FXGtsType.NodeToLinkAdjacencyInfo) binding.getModel().getAdjacencyInfo(linkPort);

            if(ntlAdjInfo != null) { //can be null during initialization
                GtsCanvasNode canvasNode = binding.getGtsCanvasNode(ntlAdjInfo.getNode());
                if (canvasNode != null) {
                    centerX += NewLinkTarget.getCenterX(canvasNode);
                    centerY += NewLinkTarget.getCenterY(canvasNode);
                    count++;
                }
            }
        }

        centerX /= count;
        centerY /= count;

        NewLinkTarget.setCenterX(centerX, this);
        NewLinkTarget.setCenterY(centerY, this);
    }

    public InvalidationListener getUpdatePositionListener() {
        return updatePositionListener;
    }

    public FXGtsLink getGtsLink() {
        return link;
    }
}
