import $ from 'jquery'
import sanitizeHtml from 'sanitize-html'
import * as sanitizeOpts from './sanitizeOpts'

const emptyEquationSelector = 'img[src="/math.svg?latex="]'
export const equationImageSelector = `img[src^="/math.svg?latex="]:not(${emptyEquationSelector}), img[src^="data:image/svg+xml"]`
const screenshotImageSelector =
    'img[src^="/screenshot/"], img[src^="data:image/png"], img[src^="data:image/gif"], img[src^="data:image/jpeg"]'

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

function stripDivsFromRichTextAnswer(answerContentValue) {
    const parent = document.createElement('div')
    parent.innerHTML = answerContentValue

    do {
        let lastNodeType
        for (let i = 0; i < parent.childNodes.length; i++) {
            const node = parent.childNodes[i]
            if (node.nodeName === 'DIV') {
                if (lastNodeType === Node.TEXT_NODE) parent.insertBefore(document.createElement('br'), node)
                if (node.lastChild && node.lastChild.nodeName !== 'BR')
                    node.insertBefore(document.createElement('br'), null)
                while (node.childNodes.length) parent.insertBefore(node.firstChild, node)
                parent.removeChild(node)
            }
            lastNodeType = node.nodeType
        }
    } while (Array.prototype.some.call(parent.childNodes, node => node.nodeName === 'DIV'))

    return parent.innerHTML
}

export function sanitize(html) {
    return sanitizeHtml(
        stripDivsFromRichTextAnswer(
            sanitizeHtml(convertLinksToRelative(html), { ...sanitizeOpts, allowedTags: ['div', 'img', 'br'] })
        ),
        sanitizeOpts
    )
}
export function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

export function isKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))
}

export function isCtrlKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))
}

function keyOrKeyCode(e, val) {
    return typeof val === 'string' ? e.key === val : e.keyCode === val
}
function preventIfTrue(e, val) {
    if (val) e.preventDefault()
    return val
}

export function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    const scrollPos = $(window).scrollTop()
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()
    $(window).scrollTop(scrollPos)

    const html = sanitize($answerElement.html())

    const answerConsideredEmpty =
        text.trim().length +
            $answerElement.find(equationImageSelector).length +
            $answerElement.find(screenshotImageSelector).length ===
        0

    return {
        answerHTML: answerConsideredEmpty ? '' : stripBrsAndTrimFromEnd(html),
        answerText: stripWitespaceFromEnd(text),
        imageCount: existingScreenshotCount($(`<div>${html}</div>`))
    }
}

function stripBrsAndTrimFromEnd(answerHtml) {
    return answerHtml.replace(/(\s|<br ?\/?>)*$/g, '')
}

function stripWitespaceFromEnd(answerHtml) {
    return answerHtml.replace(/(\s)*$/g, '')
}

export function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    range.setStartAfter(img)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

export function existingScreenshotCount($editor) {
    return $editor.find(screenshotImageSelector).length
}

export function scrollIntoView($element) {
    const $window = $(window)
    const windowHeight = $window.height() - 40
    const scroll = windowHeight + $window.scrollTop()
    const pos = $element.offset().top + $element.height()
    if (scroll < pos) {
        $window.scrollTop(pos - windowHeight)
    }
}

@@ -550,32 +550,127 @@
 n, 'g'), '')%0A%7D%0A%0A
+function isBlockElement(node) %7B%0A    return node.nodeName === 'DIV' %7C%7C node.nodeName === 'P'%0A%7D%0A%0A
 function stripDi
@@ -833,20 +833,16 @@
 lastNode
-Type
 %0A       
@@ -957,39 +957,36 @@
     if (
-node.nodeName === 'DIV'
+isBlockElement(node)
 ) %7B%0A    
@@ -1005,24 +1005,41 @@
 if (lastNode
+ && lastNode.node
 Type === Nod
@@ -1049,17 +1049,72 @@
 EXT_NODE
-)
+ && /%5CS/.test(lastNode.textContent))%0A                   
  parent.
@@ -1477,28 +1477,15 @@
 Node
-Type
  = node
-.nodeType
 %0A   
@@ -1557,39 +1557,36 @@
 node =%3E 
-node.nodeName === 'DIV'
+isBlockElement(node)
 ))%0A%0A    
@@ -1801,16 +1801,21 @@
  %5B'div',
+ 'p',
  'img', 
@@ -3362,33 +3362,54 @@
 rText: strip
+NewLinesFromStartAnd
 Wite
-s
+S
 pace
+s
 FromEnd(text
@@ -3566,16 +3566,49 @@
 eplace(/
+%5E(%5Cn%7C%3Cbr ?%5C/?%3E)*/g, '').replace(/
 (%5Cs%7C%3Cbr 
@@ -3644,17 +3644,38 @@
 trip
+NewLinesFromStartAnd
 Wite
-s
+S
 pace
+s
 From
@@ -3723,16 +3723,39 @@
 eplace(/
+%5E(%5Cn)*/g, '').replace(/
 (%5Cs)*$/g

Transform p-tags to br's and don't render extra br elements