// This is to be used by the WKWebView in PersistencePrototype only.
// It assumes that this is loaded once the DOM itself is ready.

/**
 
 *extraStyles* placeholder is reserved by WebViewLoader for injecting any custom styles
 
 */

window.onload = function () {
    
    //-- CSS Styles
    
    var styles = document.createElement("style");
    styles.textContent = ".dl-mail-quote {display: none;}\
    .dl-mail-quote .dl-mail-quote {display: block;}\
    body {margin: 0; padding: 0; font-family:-apple-system; font-size:16px; -webkit-text-size-adjust: 100%;}\
    /*extraStyles*/";
    
    // we assume that head is available here (which will definitely be the case if content is passed through HTMLKit).
    var head = document.querySelector("head");
    head.appendChild(styles);
    
    
    //-- The real Javascript code
    
    // this check is not working as intended. So we do that weird trick of .insertBefore
    if (document.querySelector(".dl-mail-quote")) {
        hasHiddenQuotedText(true)
    }
    
    resizeWindow();
    
    window.webkit.messageHandlers.loaded.postMessage(document.body.innerHTML);
    
    let editableDiv = document.querySelector("[contenteditable]:not([contenteditable=false])");
    
    if (editableDiv) {
        editableDiv.focus();
    }
    
    editableDiv.addEventListener('drop', handlePaste);
}

window.onresize = function() {
    resizeWindow();
}

function showQuotes() {
    document.querySelector(".dl-mail-quote").style.display = "block";
    
    hasHiddenQuotedText(false)
    resizeWindow();
}


function resizeWindow() {
    var wrapperDiv = document.querySelector(".dl-mail-body-wrapper")
    
    if (wrapperDiv) {
        window.webkit.messageHandlers.sizeNotification?.postMessage({width: wrapperDiv.scrollWidth, height: wrapperDiv.scrollHeight});
    }
    else {
        // fallback
        window.webkit.messageHandlers.sizeNotification?.postMessage({width: document.body.scrollWidth, height: document.body.scrollHeight});
    }
}

function hasHiddenQuotedText(hidden) {
    window.webkit.messageHandlers.quotedText.postMessage({hiddenQuotedText: hidden});
}

function getCursorPosition() {
    var x = 0, y = 0;
    var sel = window.getSelection();
    if (sel.rangeCount) {

        var range = sel.getRangeAt(0);
        var needsToWorkAroundNewlineBug = (range.startContainer.nodeName.toLowerCase() == 'p' || range.startContainer.nodeName.toLowerCase() == 'div');

        if (needsToWorkAroundNewlineBug) {
            x = range.startContainer.offsetLeft;
            y = range.startContainer.offsetTop;
        } else {
            if (range.getClientRects) {
                var rects = range.getClientRects();
                if (rects.length > 0) {
                    x = rects[0].left;
                    y = rects[0].top;
                }
            }
        }
    }

    window.webkit.messageHandlers.editor.postMessage({yPos: y});
}

function handlePaste(event) {
    let sourceObj = event.clipboardData || window.clipboardData || event.dataTransfer;
    let containsFiles = sourceObj.files.length != 0
    
    // If it is an image, it needs to be handled by the EditableWebViewLoader. If it is text, it can be handled by the system.
    if (containsFiles) {
        if (event.type === "drop") {
            let dropRange = document.caretRangeFromPoint(event.clientX, event.clientY);
            let selection = document.getSelection();
            selection.removeAllRanges();
            selection.addRange(dropRange);
        }
        
        window.webkit.messageHandlers.paste.postMessage(event.type === "drop" ? "drop" : "image");
        
        event.preventDefault();
    }
}
