document.addEventListener('DOMContentLoaded', function () {
    const canvas = document.querySelector('.vis-canvas')

    const nodes = new vis.DataSet([])
    const edges = new vis.DataSet([])

    const network = new vis.Network(canvas, {
        nodes: nodes,
        edges: edges
    }, {
        manipulation: true
    })

    const instanceLabel = (inst, schema) => `${inst.name}\n${schema.name}`

    const addNode = (toAdd) => {
        try {
            nodes.add({
                id: toAdd.uuid,
                label: instanceLabel(toAdd, toAdd.schema)
            })
        } catch(e) {
            console.debug(e)
        }
    }
    const addOutEdges = (fromId, toAdd) => {
        toAdd.forEach((inst) => {
            try {
                edges.add({
                    from: fromId,
                    to: inst.uuid,
                    label: inst['link-name'],
                    arrows: {
                        to: {enabled: true}
                    }
                })
            } catch (e) {
                console.debug(e)
            }
        })
    }
    const addLinkedNodes = (toAdd) => {
        toAdd.forEach((inst) => {
            try {
                console.debug(inst.name)
                nodes.add({
                    id: inst.uuid,
                    label: instanceLabel(inst, inst.schema)
                })
            } catch (e) {
                console.debug(e)
            }
        })
    }

    const addInstance = (instance) => {
        addNode(instance)
        addLinkedNodes(instance['links-out'])
        addOutEdges(instance.uuid, instance['links-out'])
    }

    fetch(canvas.getAttribute('data-instance-url'))
        .then((resp) => resp.json())
        .then((json) => {
            addInstance(json)
        })

    const searchForm = document.querySelector('.search')
    const searchUrl = searchForm.getAttribute('action')
    searchForm.addEventListener('submit', (event) => {
        event.preventDefault()
        const term = searchForm.querySelector('[name=term]').value
        fetch(searchUrl + encodeURIComponent(term))
            .then((resp) => resp.json())
            .then((json) => {
                console.debug(json)
                json.forEach((inst) => {
                    addInstance(inst)
                })
            })
    })
})
