// Whether or not we are viewing an editable object
let editable = false;

// Handle OCCAM events
window.addEventListener('message', function(event) {
    let message = event.data;
    if (message.name === 'updateConfiguration') {
        // TODO: Update configuration
    }
    else if (message.name === 'updateStatus') {
        // TODO: Update status configuration
    }
    else if (message.name === 'updateInput') {
        let objectInfo = message.data;

        if (objectInfo.link) {
            // Ensure link is not preserved on save
            delete objectInfo.link;

            // This object is staged and editable.
            editable = true;
        }
        else {
            editable = false;
        }

        if (objectInfo.url) {
            // Update to add a 'source' query parameter
            let reformedURL = window.location.href.replace("viewer.html", "replayweb.page/index.html");
            const url = new URL(reformedURL);
            const urlParams = new URLSearchParams();

            // Remove query parameters from object url
            let objectURL = new URL('http://localhost' + objectInfo.url);
            urlParams.set('source', objectURL.pathname);

            url.search = '?' + urlParams.toString();
            let gotoURL = url.href;

            if (objectInfo.metadata && objectInfo.metadata.general && objectInfo.metadata.general.url) {
                let targetURL = objectInfo.metadata.general.url;
                console.log('Replay Widget: Seeing embedded URL:', targetURL);
                let innerParams = new URLSearchParams();
                innerParams.set('url', targetURL);
                gotoURL = gotoURL + '#' + innerParams.toString();
            }
            console.log('Replay Widget: Loading:', gotoURL);
            window.location.href = gotoURL;
        }
    }
});

// Request configuration data.
window.parent.postMessage({
    'name': 'updateConfiguration'
}, '*');

// Request input file (if any)
window.parent.postMessage({
    'name': 'updateInput',
    'data': {}
}, '*');
