#!/usr/bin/env python3
#                                                         -*- coding: utf-8 -*-
#! \file    ./docs/conf.py
#! \author  Jiří Kučera, <sanczes@gmail.com>
#! \stamp   2015-05-01 19:51:44 (UTC+01:00, DST+01:00)
#! \project DoIt!: Tools and Libraries for Building DSLs
#! \license MIT
#! \version 0.0.0
#! \fdesc   @pyfile.docstr
#
"""\
DoIt! documentation build configuration file.\
"""

__license__ = """\
Copyright (c) 2014 - 2017 Jiří Kučera.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.\
"""

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.dirname(os.getcwd()))

# =============================================================================
# == General configuration                                                   ==

# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
  "sphinx.ext.autodoc",
  "sphinx.ext.intersphinx",
  "sphinx.ext.graphviz"
]
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
graphviz_dot = 'dot'
graphviz_dot_args = []
graphviz_output_format = 'png'

# Add any paths that contain templates here, relative to this directory.
templates_path = [ "templates" ]

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
source_encoding = 'utf-8'

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "DoIt!"
copyright = "2014 - 2015, Jiří Kučera"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.0'
# The full version, including alpha/beta/rc tags.
release = '0.0.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = "%Y-%m-%d"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [ "build" ]

# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
keep_warnings = False

# Order the functions in the documentation in the order they are defined in the
# source code.
autodoc_member_order = 'bysource'

rst_prolog = """
.. |doit| replace:: `DoIt!`
"""

# =============================================================================
# == Options for HTML output                                                 ==

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = "DoIt!'s Documentation"

# A shorter title for the navigation bar.  Default is the same as html_title.
html_short_title = ""

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = [ "static" ]

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = "%Y-%m-%d"

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {}

# If false, no module index is generated.
html_domain_indices = True

# If false, no index is generated.
html_use_index = True

# If true, the index is split into individual pages for each letter.
html_split_index = False

# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
html_file_suffix = '.html'

# Output file base name for HTML help builder.
htmlhelp_basename = 'doit-lang'

# Sphinx customization.
def setup(app):
    from docutils import nodes
    from sphinx.ext.autodoc import MethodDocumenter, add_documenter
    from sphinx.domains.python import PyXrefMixin, PyObject
    from sphinx.locale import _
    from sphinx.util.docfields import GroupedField
    from sphinx.writers.html import SmartyPantsHTMLTranslator

    class PyXrefGroupedField(PyXrefMixin, GroupedField):
        pass
    #-class

    class MethodDocumenterNoDecoratedPrivateMembers(MethodDocumenter):
        """Converts names like '_Class__private' to '__private'.
        """

        def format_name(self):
            objpath = self.objpath[:]
            if len(objpath) >= 2:
                class_name = objpath[-2]
                method_name = objpath[-1]
                if method_name.startswith("_%s" % class_name):
                    objpath[-1] = method_name[1 + len(class_name):] \
                                  or method_name
            return '.'.join(objpath) or self.modname
        #-def
    #-class

    add_documenter(MethodDocumenterNoDecoratedPrivateMembers)

    # Patch PyObject.doc_field_types:
    item = 0
    for field in PyObject.doc_field_types:
        if field.name == 'exceptions':
            break
        item += 1
    if item < len(PyObject.doc_field_types):
        PyObject.doc_field_types[item] = PyXrefGroupedField(
            field.name,
            label = field.label,
            rolename = field.rolename,
            names = field.names,
            can_collapse = field.can_collapse
        )

    # Patch Sphinx bug #1788:
    class CorrectedHTMLTranslator(SmartyPantsHTMLTranslator):

        def __init__(self, *args, **kwargs):
            SmartyPantsHTMLTranslator.__init__(self, *args, **kwargs)
        #-def

        def depart_caption(self, node):
            self.body.append('</span>')

            # append permalink if available
            if isinstance(node.parent, nodes.container) \
            and node.parent.get('literal_block'):
                self.add_permalink_ref(
                    node.parent, _('Permalink to this code')
                )
            elif isinstance(node.parent, nodes.figure):
                image_nodes = node.parent.traverse(nodes.image)
                target_node = image_nodes and image_nodes[0] or node.parent
                self.add_permalink_ref(
                    target_node, _('Permalink to this image')
                )
            elif node.parent.get('toctree'):
                self.add_permalink_ref(
                    node.parent.parent, _('Permalink to this toctree')
                )

            if isinstance(node.parent, nodes.container) \
            and node.parent.get('literal_block'):
                self.body.append('</div>\n')
            else:
                SmartyPantsHTMLTranslator.__bases__[0].__bases__[0] \
                    .depart_caption(self, node)
        #-def
    #-class

    def process_signature(
        app, what, name, obj, options, signature, return_annotation
    ):
        if what != 'function':
            return signature, return_annotation
        params = []
        # We suppose that we have not something like this:
        #
        #     def fnc(x, y, z = "Hello, World!", g = "== Problem? =="):
        #         ...
        #
        for p in [p.strip() for p in signature[1:-1].split(',')]:
            if '=' not in p:
                params.append(p)
                continue
            key, value = p.split('=')
            s, e = "<class '", "'>"
            if not value.startswith(s) or not value.endswith(e):
                params.append(p)
                continue
            value = value[len(s):-len(e)]
            if '.' not in value or '.' not in name \
            or name.split('.')[:-1] != value.split('.')[:-1]:
                params.append('='.join([key, value]))
                continue
            # `value` is from the same module as `name`:
            params.append('='.join([key, value.split('.')[-1]]))
        return "(%s)" % ', '.join(params), return_annotation
    #-def

    app.set_translator('html', CorrectedHTMLTranslator)
    app.add_stylesheet('custom.css')
    app.connect('autodoc-process-signature', process_signature)
#-def

if __name__ == '__main__':
    sys.stdout.write(html_file_suffix)
    exit(0)
#-if
