# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Previously Haka Domain (https://github.com/haka-security/haka)
# Written by Haka team

import re

from docutils import nodes
from docutils.parsers.rst import directives

from sphinx import addnodes
from sphinx.roles import XRefRole
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType, Index
from sphinx.directives import ObjectDescription
from sphinx.util.nodes import make_refnode
from sphinx.util.compat import Directive
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.writers.html import HTMLTranslator


# Fix parameter display when using something different than '()'

def new_visit_desc_parameterlist(self, node):
    if hasattr(node, 'param_class'):
        param_class = ' class="param_start_%s"' % node.param_class
    else:
        param_class = ''

    if hasattr(node, 'param_start'):
        value = node.param_start
    else:
        value = '('

    self.body.append('<big%s>%s</big>' % (param_class, value))
    self.first_param = 1
    self.optional_param_level = 0
    # How many required parameters are left.
    self.required_params_left = sum([isinstance(c, addnodes.desc_parameter)
                                     for c in node.children])
    self.param_separator = node.child_text_separator

def new_depart_desc_parameterlist(self, node):
    if hasattr(node, 'param_class'):
        param_class = ' class="param_end_%s"' % node.param_class
    else:
        param_class = ''

    if hasattr(node, 'param_end'):
        value = node.param_end
    else:
        value = ')'

    self.body.append('<big%s>%s</big>' % (param_class, value))

HTMLTranslator.visit_desc_parameterlist = new_visit_desc_parameterlist
HTMLTranslator.depart_desc_parameterlist = new_depart_desc_parameterlist

def _desc_parameterlist(argstart, argend):
    node = addnodes.desc_parameterlist()
    node.param_start = argstart
    node.param_end = argend
    return node

def _pseudo_parse_arglist(signode, argstart, arglist, argend):
    """"Parse" a list of arguments separated by commas.

    Arguments can have "optional" annotations given by enclosing them in
    brackets.  Currently, this will split at any comma, even if it's inside a
    string literal (e.g. default argument value).
    """
    paramlist = _desc_parameterlist(argstart, argend)
    stack = [paramlist]
    for argument in arglist.split(','):
        argument = argument.strip()
        ends_open = ends_close = 0
        while argument.startswith('['):
            stack.append(addnodes.desc_optional())
            stack[-2] += stack[-1]
            argument = argument[1:].strip()

        while argument.startswith(']'):
            stack.pop()
            argument = argument[1:].strip()

        while argument.endswith(']'):
            ends_close += 1
            argument = argument[:-1].strip()

        while argument.endswith('['):
            ends_open += 1
            argument = argument[:-1].strip()

        if argument:
            stack[-1] += addnodes.desc_parameter(argument, argument)
            while ends_open:
                stack.append(addnodes.desc_optional())
                stack[-2] += stack[-1]
                ends_open -= 1

            while ends_close:
                stack.pop()
                ends_close -= 1

    if len(stack) != 1:
        raise IndexError

    signode += paramlist