const options = [

];

const connections = [

];

var connectionsMade = [];
var canvas = null;
var instance = null;
var lastId = 0;
var endpointsObject = {};


var exampleDropOptions = {
    tolerance: "touch",
    hoverClass: "dropHover",
    activeClass: "dragActive"
};

var color = "#1aa8ad";
var mainEndpoint = {
    endpoint: "Rectangle",
    paintStyle: { width: 25, height: 21, fill: color },
    source: true,
    reattach: false,
    scope: "blue",
    connector: {type:"Bezier"},
    // connectorStyle: {
    //     strokeWidth: 5,
    //     stroke: color,
    //     dashstyle: "2 2"
    // },
    maxConnections: 10,
    target: false,
    dropOptions: exampleDropOptions
};


function addNewNode(content = 'Αντικείμενο', top = '', left = '')
{
    const div = document.createElement('DIV');
    const divDelete = document.createElement('DIV');
    const input = document.createElement('INPUT');
    const img = document.createElement('IMG');
    div.classList.add('window');

    lastId++;

    img.src="./delete.png";
    img.classList.add('delete-btn');
    divDelete.appendChild(img);
    divDelete.classList.add('delete');
    divDelete.classList.add('delete-btn');
    // divDelete.setAttribute('onclick', 'deleteNode()');
    // div.addEventListener('click', deleteNode);

    div.id = `id${lastId}`;

    input.value = content;
    div.appendChild(input);
    div.appendChild(divDelete);
    div.style.left = (10 + lastId * 3) + 'px'

    if(left == '')
        div.style.left = (10 + lastId * 3) + 'px'
    else
        div.style.left = left;

    if(top == '')
        div.style.top = (50 + lastId * 3) + 'px';
    else
        div.style.top = top;

    canvas.appendChild(div);

    endpointsObject[lastId] = instance.addEndpoint(div, { anchor: [1, 0.2, 1, 0] }, mainEndpoint);
    // instance.bind('beforeDrop', beforeDrop);

}

function deleteNode(ev)
{
    if(ev.target.classList.contains('delete-btn'))
    {
        const parentNode = ev.target.parentNode.parentNode;
        instance.deleteEndpoint(endpointsObject[parentNode.id.replace('id', '')]);
        parentNode.remove();

    }
    return;
}



// function addTextInput()
// {
//     const hasInput = this.querySelectorAll('input');
//     if(hasInput.length == 0)
//     {
//         console.log(this);
//         const text = this.innerText;
//         console.log(text);
//         this.innerHTML = '<input value="'+text+'"/>';
//     }
// }

window.addEventListener('load', function(){
    const windowWidth = window.innerWidth;
    const containerWidth = 200;
    const itemsPerRow = Math.floor(windowWidth / containerWidth);
    canvas = document.querySelector('#canvas');
    // canvas.addEventListener('tap', deleteNode);
    let shuffledOptions = JSON.parse(JSON.stringify(options));
    shuffle(shuffledOptions);
    for (let i = 0; i < shuffledOptions.length; i++) {
        const div = document.createElement('DIV');
        div.classList.add('window');

        if(typeof shuffledOptions[i].class != 'undefined')
            div.classList.add(shuffledOptions[i].class);

        div.id = shuffledOptions[i].id;
        div.appendChild(document.createTextNode(shuffledOptions[i].name));
        div.style.left = `${i % itemsPerRow * containerWidth}px`
        div.style.top = `${Math.floor(i / itemsPerRow) * containerWidth}px`
        canvas.appendChild(div);
    }
    load();
    addNewNode('Επικινδυνότητα', '10px', '230px');
    addNewNode('Επίπεδο πλημμύρας', '140px', '10px');

    connectInstances('#id1', '#id2');
});

function shuffle(array) {
    let currentIndex = array.length;
  
    // While there remain elements to shuffle...
    while (currentIndex != 0) {
  
      // Pick a remaining element...
      let randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
  
      // And swap it with the current element.
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }
  }
function connectInstances(id1, id2){
    let connectObject = {
        source:document.querySelector(id1),
        target:document.querySelector(id2),
        anchors:[ "AutoDefault", "AutoDefault"],
        connector: {
            type: "Bezier"
        },
                // paintStyle: { width: 25, height: 21, fill: '#1aa8ad' },
        connectorStyle: {
            strokeWidth: 5,
            stroke: color,
            dashstyle: "2 2"
        },
    };
    instance.connect(connectObject)
}

function beforeDrop(ci)
{
    // console.log(ci);

    for (let i = 0; i < connectionsMade.length; i++)
        if(connectionsMade[i].includes(ci.sourceId) && connectionsMade[i].includes(ci.targetId))
            return false;

    if(ci.sourceId == ci.targetId)
        return false;




    let connectObject = {
        source:document.querySelector(`#${ci.sourceId}`),
        target:document.querySelector(`#${ci.targetId}`),
        anchors:[ "AutoDefault", "AutoDefault"],
        connector: {
            type: "Bezier"
        },
        // paintStyle: { width: 25, height: 21, fill: '#1aa8ad' },
        connectorStyle: {
            strokeWidth: 5,
            stroke: color,
            dashstyle: "2 2"
        },
    };


    const overlayText = prompt("Όνομασία σύνδεσης");
    if(overlayText != "")
        connectObject['overlays'] = [ 
            { type:"Arrow", options:{location:1}},
            { 
                type:"Label", 
                options:{ label:overlayText, location:0.25, id:`${ci.sourceId}${ci.targetId}` }
            }
        ]

    instance.connect(connectObject)


    // console.log([ci.sourceId, ci.targetId]);

    // connectionsMade.push([ci.sourceId, ci.targetId]);
    return false;
}

function moveEnd(test)
{
    console.log(test);
}

function load() {



    jsPlumb.ready(() => {
        instance = jsPlumb.newInstance(
            {
                container: document.querySelector('.jtk-demo-canvas'),
                dragOptions: { cursor: 'pointer', zIndex: 2000 },
                // paintStyle: { stroke: '#666' },
                // paintStyle: {  fill:"red", outlineStroke:"black", outlineWidth:1  },
                sourceEndpointStyle: { fillStyle: '#808000' },

                // connectorStyle:{lineWidth:4,strokeStyle:"#567F9F",joinstyle:"round",outlineColor:"white",outlineWidth:2},

                
                endpointHoverStyle: { fill: "orange" },
                hoverPaintStyle: { stroke: "orange" },
                endpoint: "Rectangle",
                // ConnectionsDetachable:false,
                anchors: ["AutoDefault", "AutoDefault"],
                container: canvas,
                dropOptions:{activeClass:"dragActive", hoverClass:"dropHover"},
                connectionOverlays:[
                    {
                        type:"Arrow",
                        options:{location:1}
                    }
                ]
            }
        );



        // suspend drawing and initialise.
        instance.batch(function () {

            // configure some drop options for use by all endpoints.
            const items = document.querySelectorAll('.window');
            for (let i = 0; i < items.length; i++)
                instance.addEndpoint(items[i], { anchor: [1, 0.2, 1, 0] }, mainEndpoint);

            //set targets
            instance.addTargetSelector(".window", {
                anchor:"Continuous",
            })

            instance.bind('beforeDrop', beforeDrop);
            instance.bind('mousedown', deleteNode);
        });
    });



};
