// --- 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 and padding
        let bodyStyle = window.getComputedStyle(document.body);
        var topMargin = parseInt(bodyStyle.marginTop);
        var bottomMargin = parseInt(bodyStyle.marginBottom);
        var leftMargin = parseInt(bodyStyle.marginLeft);
        var rightMargin = parseInt(bodyStyle.marginRight);
        
        let topPadding = parseInt(bodyStyle.paddingTop);
        let bottomPadding = parseInt(bodyStyle.paddingBottom);
        let leftPadding = parseInt(bodyStyle.paddingLeft);
        let rightPadding = parseInt(bodyStyle.paddingRight);

        message.wrapperWidth = wrapperDiv.scrollWidth + leftMargin + rightMargin + leftPadding + rightPadding;
        message.wrapperHeight = wrapperDiv.scrollHeight + topMargin + bottomMargin + topPadding + bottomPadding;
    }
    
    window.webkit.messageHandlers.sizeChanged.postMessage(message);
    
    lastDocumentWidth = document.documentElement.clientWidth;
}
