const options = [
    {"id": "applied_arts", "name": "Εφαρμοσμένες Τέχνες"},
    {"id": "illustration", "name": "Εικονογράφιση"},
    {"id": "graphic_design", "name": "Γραφιστική"},
    {"id": "product_design", "name": "Σχεδιασμός Προϊόντων"},
    {"id": "decoration", "name": "Διακοσμητική"},
    {"id": "textile_industry", "name": "Υφαντουργία"},
    {"id": "silversmithing", "name": "Αργυροχρυσοχοΐα"},
    {"id": "pottery", "name": "Αγγειοπλαστική"},
    {"id": "audiovisual_arts", "name": "Οπτικοακουστικές τέχνες"},
    {"id": "graffiti", "name": "Γκράφιτι"},
    {"id": "printing", "name": "Τυπογραφία"},

    {"id": "fairy_tales", "name": "Παραμύθι"},
    {"id": "graphic_art", "name": "Γραφική τέχνη"},

    {"id": "visual_identity", "name": "Οπτική ταυτότητα"},
    {"id": "logo", "name": "Λογότυπο"},

    {"id": "product", "name": "Προϊόν"},
    {"id": "functionality", "name": "Λειτουργικότητα"},

    {"id": "lighting", "name": "Φωτισμός"},
    {"id": "residence", "name": "Κατοικία"},

    {"id": "thread", "name": "Κλωστή"},
    {"id": "fabric", "name": "Ύφασμα"},

    {"id": "jewel", "name": "Κόσμημα"},
    {"id": "gold", "name": "Χρυσός"},

    {"id": "vase", "name": "Βάζο"},
    {"id": "clay", "name": "Πηλός"},

    {"id": "sound", "name": "Ήχος"},
    {"id": "video", "name": "Βίντεο"},

    {"id": "mural", "name": "Τοιχογραφία"},
    {"id": "slogan", "name": "Σύνθημα"},

    {"id": "print", "name": "Εκτύπωση"},
    {"id": "font", "name": "Γραμματοσειρά"},
];

const connections = [
    ["applied_arts", "illustration"],
    ["applied_arts", "graphic_design"],
    ["applied_arts", "product_design"],
    ["applied_arts", "decoration"],
    ["applied_arts", "textile_industry"],
    ["applied_arts", "silversmithing"],
    ["applied_arts", "pottery"],
    ["applied_arts", "audiovisual_arts"],
    ["applied_arts", "graffiti"],
    ["applied_arts", "printing"],

    ["illustration", "fairy_tales"],
    ["illustration", "graphic_art"],

    ["graphic_design", "visual_identity"],
    ["graphic_design", "logo"],

    ["product_design", "product"],
    ["product_design", "functionality"],
    
    ["decoration", "lighting"],
    ["decoration", "residence"],

    ["textile_industry", "thread"],
    ["textile_industry", "fabric"],

    ["silversmithing", "jewel"],
    ["silversmithing", "gold"],

    ["pottery", "vase"],
    ["pottery", "clay"],

    ["audiovisual_arts", "sound"],
    ["audiovisual_arts", "video"],

    ["graffiti", "mural"],
    ["graffiti", "slogan"],

    ["printing", "print"],
    ["printing", "font"],
];

var connectionsMade = [];

window.addEventListener('load', function(){
    const windowWidth = window.innerWidth;
    const containerWidth = 200;
    const itemsPerRow = Math.floor(windowWidth / containerWidth);
    const canvas = document.querySelector('#canvas');
    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');
        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();
});

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 load() {



    jsPlumb.ready(() => {
        const 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: ["TopCenter", "TopCenter"],
                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.
            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
            };
           
            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', function(ci){ // Before new connection is created
                console.log(ci);

                found = false;
                let connectionToBeMade = [];
                for (let i = 0; i < connections.length; i++)
                {
                    if(connections[i].includes(ci.sourceId) && connections[i].includes(ci.targetId) && ci.sourceId != ci.targetId)
                    {
                        found = true;
                        connectionToBeMade = connections[i];
                        break;
                    }
                }

                console.log(found);
                //stop here
                if(!found)
                    return false;

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

                if(!found)
                    return false;

                connectionsMade.push(connectionToBeMade);

                
                var color = "#1aa8ad";
                const el1 = document.querySelector(`#${ci.sourceId}`)
                const el2 = document.querySelector(`#${ci.targetId}`)

                let connection = instance.connect({
                    source: el1,
                    target: el2,
                    anchors:["Continuous", "Continuous"],
                    paintStyle:{ stroke:color, strokeWidth:5, dashstyle: "2 2" },
                    connector: {type:"Bezier"},
                    endpointStyle:{ fill: "#1aa8ad", outlineStroke:"ccc", outlineWidth:1 },
                    detachable:false
                })

                return false; 
            });




        });
    });

};
