<?php
/** @var Map $block */

use FiloBlu\Esb\Block\Adminhtml\Map\Map;

$events = json_encode(array_values($block->getEventList()));
$producers = json_encode(array_values($block->getProducerList()));
$consumers = json_encode(array_values($block->getConsumerList()));

?>

<div id="filoblu_esb_map"></div>

<script>
    require([
        'jquery',
        'filoblu_esb_jsplumb'
    ], function ($) {

        jsPlumb.ready(function () {

            <?php echo "var events = {$events};"; ?>
            <?php echo "var producers = {$producers};"; ?>
            <?php echo "var consumers = {$consumers};"; ?>


            console.log(events);
            // setup some defaults for jsPlumb.
            var instance = jsPlumb.getInstance({
                Endpoint: ["Dot", {radius: 2}],
                Connector: "StateMachine",
                HoverPaintStyle: {stroke: "#1e8151", strokeWidth: 2},
                ConnectionOverlays: [
                    ["Arrow", {
                        location: 1,
                        id: "arrow",
                        length: 14,
                        foldback: 0.8
                    }]

                ],
                Container: "filoblu_esb_map"
            });
            window.jsp = instance;

            var newConsumer = function (x, y, consumer) {
                var el = document.createElement("div");
                var inEp = jsPlumbUtil.uuid();

                var outEp = jsPlumbUtil.uuid();

                el.className = "filoblu_esb_element filoblu_esb_consumer";
                el.id = `consumer_${consumer.id}`;
                el.innerHTML = consumer.consumer +
                    `<div id="${outEp}" class="ep_out"></div><div id="${inEp}" class="ep_in"></div>`;
                el.style.left = x + "px";
                el.style.top = y + "px";
                instance.getContainer().appendChild(el);
                instance.draggable(el);

                var options = {
                    filter: ".ep_out",
                    connectorStyle: {stroke: "#eb5202", strokeWidth: 2, outlineStroke: "transparent", outlineWidth: 4},
                    connectionType: consumer.output_event,
                    anchor: "Right",
                    allowLoopback: false,
                    isSource: true,

                };

                instance.makeSource(el, options);

                instance.makeTarget(el, {
                    filter: ".ep_in",
                    dropOptions: {hoverClass: "dragHover"},
                    anchor: "Left",
                    connectionType: consumer.binding_event,
                    maxConnections: 1,
                    allowLoopback: false,
                });

                return el;
            };

            var newProducer = function (x, y, producer) {
                var el = document.createElement("div");
                var id = jsPlumbUtil.uuid();
                el.className = "filoblu_esb_element filoblu_esb_producer";
                el.id = `producer_${producer.id}`;
                el.innerHTML = producer.producer + "<div id=\"" + jsPlumbUtil.uuid() + "\" class=\"ep_out\"></div></div>";
                el.style.left = x + "px";
                el.style.top = y + "px";
                instance.getContainer().appendChild(el);
                instance.draggable(el);

                var options = {
                    filter: ".ep_out",
                    connectorStyle: {stroke: "#eb5202", strokeWidth: 2, outlineStroke: "transparent", outlineWidth: 4},
                    connectionType: producer.output_event,
                    anchor: "Right",
                    allowLoopback: false,
                    isSource: true,
                    maxConnections: 1000,

                };

                instance.makeSource(el, options);

                return el;
            };


            var connections = [];
            events.forEach(function (event) {

                connections[event] = {from: [], to: []};

                instance.registerConnectionType(event, {
                    //  anchor: ["Left" , "Right"],
                    connector: "StateMachine",
                    overlays: [
                        ["Label", {label: event, id: "label"}]
                    ],
                    data: {esb_event: event}
                });
            });

            var x = 100, y = 100;
            producers.forEach(function (producer) {
                var e = newProducer(x, y, producer);
                if (producer.output_event) {
                    try {
                        connections[producer.output_event].from.push(e);
                    }catch (e) {
                        console.log(e);
                    }
                }
                y += 100;
            });
            var x = 600, y = 100;
            consumers.forEach(function (consumer) {
                var e = newConsumer(x, y, consumer);
                if (consumer.output_event) {
                    connections[consumer.output_event].from.push(e);
                }

                if (consumer.binding_event) {
                    connections[consumer.binding_event].to.push(e);
                }
                y += 100;
            });


            console.log(connections);

            for (var o in connections) {

                for (var from in connections[o].from) {
                    for (var to in connections[o].to) {
                        instance.connect(
                            {
                                source: connections[o].from[from],
                                target: connections[o].to[to],
                                type: o,
                                newConnection: false
                            });
                    }
                }
            }



            instance.bind("connectionDetached", function () {
                var connections = [];
                $.each(instance.getAllConnections(), function (idx, connection) {
                    connections.push({
                        connectionId: connection.endpoints[0].connectionType,
                        pageSourceId: connection.sourceId,
                        pageTargetId: connection.targetId,
                        sourceText: connection.source.innerText,
                        targetText: connection.target.innerText,
                    });
                });

                console.log(JSON.stringify(connections));
            });
            instance.bind("connection", function () {

                var connections = [];
                $.each(instance.getAllConnections(), function (idx, connection) {
                    connections.push({
                        connectionId: connection.endpoints[0].connectionType,
                        from: connection.sourceId,
                        to: connection.targetId,

                    });
                });

                console.log(JSON.stringify(connections));


            });

        });
    });

</script>

