# -*- coding: utf-8 -*-
#
# autobahn documentation build configuration file, created by
# sphinx-quickstart on Sat Apr 30 17:26:56 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import shlex
import time

try:
    import sphinx_rtd_theme
except ImportError:
    sphinx_rtd_theme = None

try:
    from sphinxcontrib import spelling
except ImportError:
    spelling = None


# 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.abspath('./_extensions'))
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))

# monkey-patch txaio so that we can "use" both twisted *and* asyncio,
# at least at import time -- this is so the autodoc stuff can
# successfully import autobahn.twisted.* as well as autobahn.asyncio.*
# (usually, you can only import one or the other in a single Python
# interpreter)
import txaio

def use_tx():
  "monkey-patched for doc-building"
  from txaio import tx
  txaio._use_framework(tx)

def use_aio():
  "monkey-patched for doc-building"
  from txaio import aio
  txaio._use_framework(aio)

txaio.use_twisted = use_tx
txaio.use_asyncio = use_aio


# Monkey patch away WARNING like:
# "index.rst:4: WARNING: nonlocal image URI found: https://img.shields.io/pypi/v/txaio.svg"
# see: http://stackoverflow.com/a/28778969
import sphinx.environment
from docutils.utils import get_source_line

def _warn_node(self, msg, node, **kwargs):
    if not msg.startswith('nonlocal image URI found:'):
        self._warnfunc(msg, '%s:%s' % get_source_line(node))

sphinx.environment.BuildEnvironment.warn_node = _warn_node

try:
    from qualname import qualname
except ImportError:
    qualname = None

# http://stackoverflow.com/a/21449475/884770
# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#event-autodoc-skip-member

# app, what, name, obj, skip, options:
# <sphinx.application.Sphinx object at 0x2b0192ab2f90> class __module__ autobahn.asyncio.websocket True {'show-inheritance': True, 'members': <object object at 0x2b018c791710>, 'undoc-members': True}
#
def autodoc_skip_member(app, what, name, obj, skip, options):
    # skip everything that isn't decorated with @autobahn.public or ..
    if hasattr(obj, '_is_public') and obj._is_public:
        if qualname:
            try:
                qn = qualname(obj)
            except AttributeError as e:
                print(e)
                qn = name
            print('public API: {}.{}'.format(obj.__module__, qn))
        return False
    else:
        return True

# !! when enabled, only members with "@public" decorator will be rendered in the docs !!
# def setup(app):
#     # wire up our custom checker to skip member
#     app.connect('autodoc-skip-member', autodoc_skip_member)


# -- General configuration ------------------------------------------------

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

autoapi_type = 'python'
autoapi_dirs = ['../autobahn']
autoapi_ignore = [
    '*test*',
    'test_*.py',
    '../autobahn/test/*',
    '../autobahn/wamp/test/*',
    '../autobahn/websocket/test/*',
    '../autobahn/test/test_*.py',
    '../autobahn/wamp/test/test_*.py',
    '../autobahn/websocket/test/test_*.py',
    'autoapi/autobahn/test/*',
    'autoapi/autobahn/websocket/test/*',
    'autoapi/autobahn/wamp/test/*',
]
autoapi_add_toctree_entry = False
autoapi_options = ['members', 'undoc-members', 'private-members', 'show-inheritance', 'special-members', 'show-module-summary']
# autoapi_template_dir = 'docs/autoapi/templates'
autoapi_python_use_implicit_namespaces = True


# Check if we are building on readthedocs
RTD_BUILD = os.environ.get('READTHEDOCS', None) == 'True'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    # https://sphinx-autoapi.readthedocs.io
    'autoapi.extension',

    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx.ext.ifconfig',
    'sphinx.ext.todo',
    'sphinx.ext.doctest',

    # Usage:            .. thumbnail:: picture.png
    # Installation:     pip install sphinxcontrib-images
    # Source:           https://github.com/sphinx-contrib/images
    'sphinxcontrib.images',

    #'sphinxcontrib.spelling',
    'txsphinx'
]

# extensions not available on RTD
if spelling is not None:
    extensions.append('sphinxcontrib.spelling')

spelling_lang = 'en_US'
spelling_show_suggestions = False
spelling_word_list_filename = 'spelling_wordlist.txt'

# 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-sig'

# The master toctree document.
master_doc = 'contents'

# General information about the project.
project = 'autobahn'
author = 'Crossbar.io Project'
this_year = '{0}'.format(time.strftime('%Y'))
if this_year != '2012':
    copyright = '2012-{0}, Crossbar.io Technologies GmbH'.format(this_year)
else:
    copyright = '2012, Crossbar.io Technologies GmbH'

# The version info for the project yo're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
with open(os.path.join(base_dir, "autobahn", "_version.py")) as f:
   exec(f.read())  # defines __version__

version = release = __version__

# 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 = '%B %d, %Y'

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

# 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

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False


# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
if sphinx_rtd_theme:
    html_theme = "sphinx_rtd_theme"
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
    html_theme = "default"

# 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 = None

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

# 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 = []

# 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 = '%b %d, %Y'

# 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.
# Show full, global TOC in sidebar
# http://stackoverflow.com/a/19007358
# http://sphinx-doc.org/config.html#confval-html_sidebars
html_sidebars = {
    '**': [
        'globaltoc.html',
        'relations.html',
        'sourcelink.html',
        'searchbox.html'
    ],
}

# 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 = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'autobahndoc'

# http://sphinx-doc.org/ext/intersphinx.html
intersphinx_mapping = {
   'py3': ('https://docs.python.org/3', None),
   'python': ('https://docs.python.org/3', None),
   'rtd': ('https://docs.readthedocs.io/en/latest/', None),
   'txaio': ('https://txaio.readthedocs.io/en/latest/', None),
   'autobahn': ('https://autobahn.readthedocs.io/en/latest/', None),
   'zlmdb': ('https://zlmdb.readthedocs.io/en/latest/', None),
}

rst_epilog = """
.. |ab| replace:: Autobahn
.. |Ab| replace:: **Autobahn**
.. |abL| replace:: Autobahn|Python
.. |AbL| replace:: **Autobahn**\|Python
.. _Autobahn: http://crossbar.io/autobahn#python
.. _AutobahnJS: http://crossbar.io/autobahn#js
.. _AutobahnPython: **Autobahn**\|Python
.. _WebSocket: http://tools.ietf.org/html/rfc6455
.. _RFC6455: http://tools.ietf.org/html/rfc6455
.. _WAMP: http://wamp-proto.org/
.. _Twisted: http://twistedmatrix.com/
.. _asyncio: http://docs.python.org/3.4/library/asyncio.html
.. _CPython: http://python.org/
.. _PyPy: http://pypy.org/
.. _Jython: http://jython.org/
.. _AutobahnTestsuite: http://crossbar.io/autobahn#testsuite
.. _trollius: https://pypi.python.org/pypi/trollius/
.. _tulip: https://pypi.python.org/pypi/asyncio/
"""

rst_prolog = """
"""

# http://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method
autoclass_content = 'both'

# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#confval-autodoc_member_order
# autodoc_member_order = 'bysource'
