let currentScrollRef = "" // ref of the scroll currently displayed 

function RenderScroll() {
    const dataSource = document.querySelector("#Unity-Data-Interface")
    if (!(dataSource instanceof HTMLElement)
        || dataSource === null
        || dataSource.dataset.scrollDynamic === undefined
    ) {
        console.error("No Scroll found in the Unity-Data-Interface")
        return
    }
    const scroll_json = JSON.parse(dataSource.dataset.scrollDynamic);
    let scroll: Backend_Object 
    try {
        scroll = backendObject_fromJSON(scroll_json)
        if (!Scroll.isScroll(scroll)) {throw {} }
    } catch (error) {
        console.error(error, `Cannot parse the scroll:`, scroll_json)
        return
    }
    //console.log(scroll.requiredFacts);
    const scrollContainer = document.querySelector("#scrollContainer");

    // replace the description if the scroll changed, otherwise only its content needs update
    // if (scroll.ref != currentScrollRef) {
    //     currentScrollRef = scroll.ref;
    //     scrollContainer.innerHTML = scroll.description;
    // }

    // go through the facts in the scroll, show their labels, add dropzones and limit the allowed types
    scroll.slots.forEach(slot => {
        $(`[data-slot-id='${slot.uri}']`)
            .html(slot.label)
            .attr("dropzone", "copy")
    })

    // acquired facts only need updated labels
    scroll.acquiredFacts.forEach(fact => {
        $(`[data-solution-id='${fact.uri}']`)
            .html(fact.label)
    })
    console.log(scroll.label + 'Scroll rendered')
}


$(function () {
    RenderScroll()
});