#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config

import os
import sys
from datetime import datetime
import bcx


# -- Path setup --------------------------------------------------------------

# 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('../../'))


# -- Project information -----------------------------------------------------

# General information about the project.
project = 'Blockchain Exchange Python API'
author = 'Ilya Kisil'
year = datetime.now().year
copyright = '2020 - {}, {}'.format(year, author)

# 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 = bcx.__version__
# The full version, including alpha/beta/rc tags.
release = bcx.__version__


# -- 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.
sys.path.insert(0, os.path.abspath('_sphinx_ext'))
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.imgmath',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = [
    '_templates',
    '_templates/autosummary',
]

# The suffix(es) of source filenames.
source_suffix = [
    '.rst',
]

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

# The master toctree document.
master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# 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.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = [
    '_build',
    '_sphinx_ext',
    'Thumbs.db',
    '.DS_Store',
]

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

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

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

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

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


# -- Configuration for sphinx.ext.autosummary. Reference: http://www.sphinx-doc.org/en/master/usage/extensions/autosummary.html

# Generate autosummary even if no references
autosummary_generate = True


# -- Configuration for sphinx.ext.autodoc. Reference: http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html

# This value selects what content will be inserted into the main body of an autoclass directive.
# Available options 'init', 'class', 'both'.
autoclass_content = 'both'


# -- Configuration for parsing docstrings ------------------------------------

_docstring_formatting = "numpydoc"
if _docstring_formatting == "napoleon":
    # Reference: https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html and https://sphinxcontrib-napoleon.readthedocs.io/en/latest/
    extensions.append('sphinx.ext.napoleon')
    napoleon_numpy_docstring = True
elif _docstring_formatting == "numpydoc":
    extensions.append('numpydoc.numpydoc')
    numpydoc_class_members_toctree = False  # This is needed for some reason with 'numpydoc' see https://github.com/numpy/numpydoc/issues/69
    numpydoc_show_inherited_class_members = False
    numpydoc_attributes_as_param_list = False


# -- Configuration for 'sphinx-gallery' --------------------------------------
# This extension is used in order to include example scripts into docs
try:
    import sphinx_gallery.gen_gallery
    extensions.append('sphinx_gallery.gen_gallery')
    sphinx_gallery_conf = {
        'examples_dirs': '../../examples',           # Relative path to example scripts
        'gallery_dirs': 'generated_sphinx_gallery',  # Relative path to where to save gallery generated output
        'filename_pattern': '/run-',                 # Regex for examples to be executed during docs build
        'download_all_examples': False,              # Disable download button of all scripts at once
        'remove_config_comments': True,              # Remove the comments with file-by-file configs
        'reference_url': {
            'bcx': None,             # Add hyperlinks to the source code of used functions/classes to their matching online documentation
        },
        'doc_module': ('bcx',)
    }
except ModuleNotFoundError:
    pass


# -- Configuration for converting markdown files to rST and including them in docs
# Usage: .. mdinclude:: path/to/markdown/file
# extensions.append('m2r.m2r')
# source_suffix.append('.md')


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

# The theme to use for HTML and HTML Help pages.
import guzzle_sphinx_theme
html_theme = 'guzzle_sphinx_theme'
html_theme_path = guzzle_sphinx_theme.html_theme_path()

# Register the guzzle_sphinx_theme as an extension to generate a sitemap.xml
extensions.append("guzzle_sphinx_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 respective
# documentation.
# Guzzle theme options: https://github.com/guzzle/guzzle_sphinx_theme/blob/master/guzzle_sphinx_theme/guzzle_sphinx_theme/theme.conf
html_theme_options = {
    "google_analytics_account": os.getenv('TRACKING', False),  # hack to add tracking
    "base_url": ""
}
html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'

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

# 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 = '_static/imgs/bc-favicon.ico'

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = 'HOTTBOX: Higher Order Tensors ToolBox'

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

# 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.
html_show_sourcelink = False
html_sidebars = {
    '**': [
        'logo-text.html',
        'searchbox.html',
        'globaltoc.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


# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'blockchain_exchange_doc'


# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',

    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc,
     'blockchain_exchange_python_api.tex',
     'Blockchain Exchange Python API Documentation',
     author,
     'manual'),
]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc,
     'blockchain_exchange_python_api',
     'Blockchain Exchange Python API Documentation',
     [author],
     1),
]


# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc,
     'blockchain_exchange_python_api',
     'Blockchain Exchange Python API Documentation',
     author,
     'blockchain_exchange_python_api',
     'Blockchain Exchange Python API Documentation',
     'Miscellaneous'),
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']


# -- Custom sphinx settings   ------------------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
    'https://docs.python.org/': None
}


def rst_to_jinja(app, docname, source):
    """ Render our pages as a jinja template for fancy templating goodness.

    References
    ----------
    1.  https://www.ericholscher.com/blog/2016/jul/25/integrating-jinja-rst-sphinx/
    """
    # Make sure we're outputting HTML
    if app.builder.format != 'html':
        return
    src = source[0]
    rendered = app.builder.templates.render_string(
        src, app.config.html_context
    )
    source[0] = rendered


def add_static_files(sphinx_app, dirs):
    """

    Parameters
    ----------
    sphinx_app
    dirs : list[str]
        List of directories to look for static files.

    Notes
    -----
    Order of directories in ``dirs`` matters and defines order
    in which files from those directories will be imported to
    ``html`` files.
    """
    # We use `abspath` instead of `realpath` because this file is a target
    # for symbolic link. But we need to search for files where symbolic link
    # is located
    here = os.path.dirname(os.path.abspath(__file__))

    static_files = []
    for static_dir in dirs:
        # We do this, since CWD might vary at execution time
        # depending where this function is called
        static_dir_path = os.path.join(here, static_dir)

        for dir_item in os.listdir(static_dir_path):
            if os.path.isfile(f'{static_dir_path}/{dir_item}'):
                static_files.insert(0, dir_item)
            else:
                files = [f'{dir_item}/{file}' for file in os.listdir(f'{static_dir_path}/{dir_item}')]
                static_files.extend(files)

    for file in static_files:
        if file.endswith('.js'):
            print(f'==> Registering javascript file: [{file}]')
            sphinx_app.add_js_file(file)
        elif file.endswith('.css'):
            print(f'==> Registering stylesheet file: [{file}]')
            sphinx_app.add_css_file(file)


def setup(app):
    add_static_files(
        sphinx_app=app,
        dirs=html_static_path
    )
    app.connect("source-read", rst_to_jinja)
