window.addEventListener('load', function() {
    addAutoScaleClassToInlineImages()
});

/**
 * Adds the `dl-auto-scale` class to `img` elements that meet the selection criteria for an "inline
 * image".
 *
 * The selection criteria attempts to identify images that aren't part of an overall layout, where
 * it would be natural for larger images to be down-scaled to fit within the viewport:
 *
 * - Identify `img` elements that don't have any ancestor nodes with an explicit width set
 * - The width may be set in the node's `style`, or as a `width` attribute
 * - Ignore the `img` element itself, as Gmail sets `width` and `height` based on the image
 * - However, never auto-scale images that are already very small (1x1 tracking pixels / beacons)
 *
 * This is not limited to embedded images (using cid: urls).
 */
function addAutoScaleClassToInlineImages() {
    let maxAllowedWidth = 1; // Ignores very small images

    let allImgs = document.querySelectorAll("img");

    for (const curImg of allImgs) {
        if (curImg.width <= maxAllowedWidth && curImg.width != 0) {
            continue;
        }
        
        var curNode = curImg.parentNode;
        var hasDefinedWidth = false

        // Walk the ancestor nodes up to and including the document element.
        while (curNode && curNode !== document) {
            if (curNode.style.width || curNode.width) {
                hasDefinedWidth = true;
                break;
            }
            curNode = curNode.parentNode;
        }

        if (!hasDefinedWidth) {
            curImg.classList.add("dl-auto-scale")
        }
    }
}

function updateInlineImages(contentIdAndUrls) {
    for (let contentIdAndUrl of contentIdAndUrls) {
        var contentId = contentIdAndUrl[0];
        var url = contentIdAndUrl[1];

        var img = document.querySelector('img[src="cid:' + contentId + '"]');
        if (img) {
            img.addEventListener('load', resizeWindow); // Trigger window resize.
            img.src = url;
            img.setAttribute('dl-cid', contentId);
        }
    }
}

function setDefaultFontFamily(family) {
    for (styleSheet of document.styleSheets) {
        for (rule of styleSheet.rules) {
            if (rule.selectorText === "body" && rule.style.fontFamily !== "") {
                rule.style.fontFamily = family ? `"${family}"` : "system-ui";
            }
        }
    }
}

function setDefaultFontSize(size) {
    for (styleSheet of document.styleSheets) {
        for (rule of styleSheet.rules) {
            if (rule.selectorText === "body" && rule.style.fontSize !== "") {
                rule.style.fontSize = `${size}px`;
            }
        }
    }
}
