# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from __python__ import bound_methods, hash_literals


if document?.caretPositionFromPoint:
    caret_position_from_point = document.caretPositionFromPoint.bind(document)
else:
    caret_position_from_point = def (x, y):
        r = document.caretRangeFromPoint(x, y)
        if r:
            return {'offsetNode': r.startContainer, 'offset': r.startOffset}
        return None


def word_boundary_regex():
    ans = word_boundary_regex.ans
    if ans is undefined:
        ans = word_boundary_regex.ans = RegExp(
        '[\\s!-#%-\\x2A,-/:;\\x3F@\\x5B-\\x5D_\\x7B}\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A'
        '\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\u061F\\u066A-\\u066D\\u06D4\\u0700-\\u070D\\u07F7-'
        '\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u0AF0\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-'
        '\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB\\u1360-\\u1368\\u1400\\u166D\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6'
        '\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1BFC-\\u1BFF\\u1C3B-\\u1C3F'
        '\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2329\\u232A'
        '\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E'
        '\\u2E30-\\u2E3B\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA673\\uA67E\\uA6F2-'
        '\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0'
        '\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-'
        '\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]'
        )
    return ans


def expand_offset_to_word(string, offset):
    start = offset
    pat = word_boundary_regex()
    while start >= 1 and not pat.test(string.charAt(start - 1)):
        start -= 1
    end, sz = offset, string.length
    while end < sz and not pat.test(string.charAt(end)):
        end += 1
    return {'word': string[start:end], 'start': start, 'end': end}


def word_at_point(x, y):
    p = caret_position_from_point(x, y)
    if p and p.offsetNode?.nodeType is Node.TEXT_NODE:
        word_info = expand_offset_to_word(p.offsetNode.data, p.offset)
        if word_info.word:
            r = document.createRange()
            r.setStart(p.offsetNode, word_info.start)
            r.setEnd(p.offsetNode, word_info.end)
            return r


def first_visible_word():
    width = window.innerWidth
    height = window.innerHeight
    xdelta = width // 10
    ydelta = height // 10
    for y in range(0, height, ydelta):
        for x in range(0, width, xdelta):
            r = word_at_point(x, y)
            if r?:
                return r


def empty_range_extents():
    return {
        'start': {'x': 0, 'y': 0, 'height': 0, 'width': 0, 'onscreen': False, 'selected_prev': False},
        'end': {'x': 0, 'y': 0, 'height': 0, 'width': 0, 'onscreen': False, 'selected_prev': False}
    }

# Returns a node that we know will produce a reasonable bounding box closest to the start or end
# of the DOM tree from the specified node.
# Currently: safe_nodes and text nodes.
# This a depth first traversal, with the modification that if a node is reached that meets the criteria,
# the traversal stops, because higher nodes in the DOM tree always have larger bounds than their children.
safe_nodes = {'img': True, 'br': True, 'hr': True}


def get_selection_node_at_boundary(node, start):
    stack = []
    stack.push({'node': node, 'visited': False})
    while stack.length > 0:
        top = stack[-1]
        # If the top node is a target type, we know that no nodes below it can be more to the start or end
        # than it, so return it immediately.
        name = top.node.nodeName.toLowerCase() if top.node.nodeName else ''
        if top.node.nodeType is Node.TEXT_NODE or safe_nodes[name]:
            return top.node
        # Otherwise, depth-first traversal.
        else if top.visited:
            stack.pop()
        else:
            top.visited = True
            if top.node.childNodes:
                for c in top.node.childNodes if start else reversed(top.node.childNodes):
                    stack.push({'node': c, 'visited': False})


def range_extents(q, in_flow_mode):
    ans = empty_range_extents()
    if not q:
        return ans
    start = q.cloneRange()
    end = q.cloneRange()

    def rect_onscreen(r):
        # we use -1 rather than zero for the top limit because on some
        # platforms the browser engine returns that for top line selections.
        # See https://bugs.launchpad.net/calibre/+bug/2024375/ for a test case.
        if r.right <= window.innerWidth and r.bottom <= window.innerHeight and r.left >= 0 and r.top >= -1:
            return True
        return False

    def apply_rect_to_ans(rect, ans):
        ans.x = Math.round(rect.left)
        ans.y = Math.round(rect.top)
        ans.height = Math.round(rect.height)
        ans.width = Math.round(rect.width)
        ans.onscreen = rect_onscreen(rect)
        return ans

    def for_boundary(r, ans, is_start):
        rect = r.getBoundingClientRect()
        if rect.height is 0 and rect.width is 0:
            # this tends to happen when moving the mouse downwards
            # at the boundary between paragraphs
            if r.startContainer?.nodeType is Node.ELEMENT_NODE:
                node = r.startContainer
                if r.startOffset and node.childNodes.length > r.startOffset:
                    node = node.childNodes[r.startOffset]

                boundary_node = get_selection_node_at_boundary(node, is_start)
                # If we found a node that will produce a reasonable bounding box at a boundary, use it:
                if boundary_node:
                    if boundary_node.nodeType is Node.TEXT_NODE:
                        if is_start:
                            r.setStart(boundary_node, 0)
                            r.setEnd(boundary_node, 0)
                        else:
                            r.setStart(boundary_node, boundary_node.length)
                            r.setEnd(boundary_node, boundary_node.length)
                        rect = r.getBoundingClientRect()
                    else:
                        rect = boundary_node.getBoundingClientRect()
                        if not is_start:
                            ans.selected_prev = True
                # we can't use getBoundingClientRect as the node might be split
                # among multiple columns
                else if node.getClientRects:
                    rects = node.getClientRects()
                    if rects.length:
                        erect = rects[0]
                        rect = {'left': erect.left, 'top': erect.top, 'right': erect.left + 2, 'bottom': erect.top + 2, 'width': 2, 'height': 2}
        apply_rect_to_ans(rect, ans)

    if q.startContainer.nodeType is Node.ELEMENT_NODE:
        start.collapse(True)
        for_boundary(start, ans.start, True)
    elif q.startOffset is 0 and q.startContainer.length is 0:
        start.collapse(True)
        for_boundary(start, ans.start, True)
    elif q.startOffset is q.startContainer.length:
        start.setStart(q.startContainer, q.startOffset - 1)
        start.setEnd(q.startContainer, q.startOffset)
        rect = start.getBoundingClientRect()
        apply_rect_to_ans(rect, ans.start).selected_prev = True
    else:
        start.setStart(q.startContainer, q.startOffset)
        start.setEnd(q.startContainer, q.startOffset + 1)
        rect = start.getBoundingClientRect()
        apply_rect_to_ans(rect, ans.start)

    if q.endContainer.nodeType is Node.ELEMENT_NODE:
        end.collapse(False)
        for_boundary(end, ans.end, False)
    elif q.endOffset is 0 and q.endContainer.length is 0:
        end.collapse(False)
        for_boundary(end, ans.end, False)
    elif q.endOffset is q.endContainer.length:
        end.setStart(q.endContainer, q.endOffset - 1)
        end.setEnd(q.endContainer, q.endOffset)
        rect = end.getBoundingClientRect()
        apply_rect_to_ans(rect, ans.end).selected_prev = True
    else:
        end.setStart(q.endContainer, q.endOffset)
        end.setEnd(q.endContainer, q.endOffset + 1)
        rect = end.getBoundingClientRect()
        apply_rect_to_ans(rect, ans.end)

    if ans.end.height is 2 and ans.start.height > 2:
        ans.end.height = ans.start.height
    if ans.start.height is 2 and ans.end.height > 2:
        ans.start.height = ans.end.height
    return ans


def selection_extents(in_flow_mode):
    sel = window.getSelection()
    if not sel or not sel.rangeCount or sel.isCollapsed:
        return empty_range_extents()
    return range_extents(sel.getRangeAt(0), in_flow_mode)


def is_start_closer_to_point(pos):
    sel = window.getSelection()
    if not sel.rangeCount:
        return
    p = caret_position_from_point(pos.x, pos.y)
    if p:
        r = sel.getRangeAt(0)
        sr = document.createRange()
        sr.setStart(r.startContainer, r.startOffset)
        sr.setEnd(p.offsetNode, p.offset)
        er = document.createRange()
        er.setStart(p.offsetNode, p.offset)
        er.setEnd(r.endContainer, r.endOffset)
        return sr.toString().length < er.toString().length
    return False


def move_end_of_selection(pos, start):
    sel = window.getSelection()
    if not sel.rangeCount:
        return
    p = caret_position_from_point(pos.x, pos.y)
    if not p:
        return
    r = sel.getRangeAt(0)
    if start is None:
        q = document.createRange()
        q.setStart(p.offsetNode, p.offset)
        q.setEnd(p.offsetNode, p.offset)
        if r.compareBoundaryPoints(window.Range.START_TO_START, q) >= 0:
            start = True
        elif r.compareBoundaryPoints(window.Range.END_TO_END, q) <= 0:
            start = False
        else:
            # point is inside the selection
            start = False
    new_range = document.createRange()
    if start:
        new_range.setStart(p.offsetNode, p.offset)
        new_range.setEnd(r.endContainer, r.endOffset)
        other_boundary_changed = r.endContainer is not new_range.endContainer or r.endOffset is not new_range.endOffset
    else:
        new_range.setStart(r.startContainer, r.startOffset)
        new_range.setEnd(p.offsetNode, p.offset)
        other_boundary_changed = r.startContainer is not new_range.startContainer or r.startOffset is not new_range.startOffset
    if new_range.collapsed and other_boundary_changed:
        # we ignore the case when the new range is collapsed and the other end
        # of the selection is also moved as this is a chromium bug. See https://bugs.launchpad.net/bugs/2054934
        return
    sel.removeAllRanges()
    sel.addRange(new_range)
