// --- Listeners

window.addEventListener('DOMContentLoaded', function() {
    // Provides the initial hook to stop loading and start displaying the webview.
    resizeWindow();
});

let lastDocumentWidth = 0;

window.addEventListener('load', function() {
    resizeWindow();
    
    const resizeObserver = new ResizeObserver(() => {
        if (lastDocumentWidth != document.documentElement.clientWidth) {
            resizeWindow();
        }
    });
    
    resizeObserver.observe(document.body);
});

// --- Resizing

function resizeWindow() {
    var message = {
        bodyWidth: document.documentElement.scrollWidth,
        bodyHeight: document.documentElement.scrollHeight
    };
    
    // Also send the size of the body wrapper div, because for some messages, the body size grows to
    // fill the empty space in the webview and we want the fitting size of the content itself.
    var wrapperDiv = document.querySelector('.dl-mail-body-wrapper');
    
    // [MAIL-971] Only forward wrapperDiv's dimensions if they are non-zero. There are some message
    // bodies where the wrapperDiv's scrollHeight can't be determined, while the body's can.
    if (wrapperDiv && wrapperDiv.scrollWidth > 0 && wrapperDiv.scrollHeight > 0) {
        // Adjust for body margin
        let bodyStyle = window.getComputedStyle(document.body);
        var topMargin = parseInt(bodyStyle.getPropertyValue('margin-top'));
        var bottomMargin = parseInt(bodyStyle.getPropertyValue('margin-bottom'));
        var leftMargin = parseInt(bodyStyle.getPropertyValue('margin-left'));
        var rightMargin = parseInt(bodyStyle.getPropertyValue('margin-right'));
        
        message.wrapperWidth = wrapperDiv.scrollWidth + leftMargin + rightMargin;
        message.wrapperHeight = wrapperDiv.scrollHeight + topMargin + bottomMargin;
    }
    
    window.webkit.messageHandlers.sizeChanged.postMessage(message);
    
    lastDocumentWidth = document.documentElement.clientWidth;
}
