# -*- 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/master/config

# -- 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.
#

import os
import sys
import re
from datetime import date

sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath("../."))
sys.path.insert(0, os.path.abspath("../.."))
import recommonmark
from recommonmark.transform import AutoStructify
import autopew

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

project = "autopew"
copyright = "2019-%s, Morgan Williams & Louise Schoneveld" % date.today().year
author = "Morgan Williams & Louise Schoneveld"

version = re.findall(r"^[\d]*.[\d]*.[\d]*", autopew.__version__)[0]
release = 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.
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.doctest",
    "sphinx.ext.todo",
    "sphinx.ext.coverage",
    "sphinx.ext.mathjax",
    "sphinx.ext.intersphinx",
    "sphinx.ext.napoleon",
    "recommonmark",
    "sphinx.ext.viewcode",  # generates sourcecode on docs site, with reverse links to docs
]

napoleon_google_docstring = False
napoleon_use_param = False
napoleon_use_ivar = True

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"

# 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

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

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


# -- 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 = {"prev_next_buttons_location": None, "vcs_pageview_mode": "edit"}

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

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
html_sidebars = {
    "**": [
        "globaltoc.html",
        "sourcelink.html",
        # "relations.html",  # needs 'show_related': True theme option to display
        "searchbox.html",
    ]
}

html_context = {
    "display_github": True,  # Integrate GitHub
    "last_updated": True,
    "github_user": "morganjwilliams",  # Username
    "github_repo": "autopew",  # Repo name
    "github_version": "develop",  # Version
    "conf_py_path": "/docs/source/",  # Path in the checkout to the docs root
}


# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "autopewdoc"


# -- 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,
        "autopew.tex",
        "autopew Documentation",
        r"Morgan Williams \& Louise Schoneveld",
        "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, "autopew", "autopew 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,
        "autopew",
        "autopew Documentation",
        author,
        "autopew",
        "One line description of project.",
        "Science/Research",
    )
]


# -- intersphinx
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None),
    "numpy": ("http://docs.scipy.org/doc/numpy/", None),
    "scipy": ("https://docs.scipy.org/doc/scipy/reference/", None),
    "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),
    "matplotlib": ("https://matplotlib.org/", None),
}


github_doc_root = "https://github.com/morganjwilliams/autopew/tree/develop/docs/"
# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

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


# -- Extension configuration -------------------------------------------------

# -- Options for intersphinx extension ---------------------------------------

# Example configuration for intersphinx: refer to the Python standard library.

rst_prolog = """
.. |br| raw:: html

   <br />

.. |year| raw:: html

    {year}

.. |version| raw:: html

    {version}

""".format(
    year=str(date.today().year), version=version
)

rst_prolog += """

.. raw:: html

  <a href="https://github.com/morganjwilliams/pyrolite"
     class="github-corner"
     aria-label="View source on GitHub">
  <svg width="80"
       height="80"
       viewBox="0 0 250 250"
       style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;"
       aria-hidden="true">
       <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
       <path d="M128.3,109.0
                C113.8,99.7 119.0,89.6 119.0,89.6
                C122.0,82.7 120.5,78.6 120.5,78.6
                C119.2,72.0 123.4,76.3 123.4,76.3
                C127.3,80.9 125.5,87.3 125.5,87.3
                C122.9,97.6 130.6,101.9 134.4,103.2"
       fill="currentColor"
       style="transform-origin: 130px 106px;"
       class="octo-arm"></path>
       <path d="M115.0,115.0
                C114.9,115.1 118.7,116.5 119.8,115.4
                L133.7,101.6
                C136.9,99.2 139.9,98.4 142.2,98.6
                C133.8,88.0 127.5,74.4 143.8,58.0
                C148.5,53.4 154.0,51.2 159.7,51.0
                C160.3,49.4 163.2,43.6 171.4,40.1
                C171.4,40.1 176.1,42.5 178.8,56.2
                C183.1,58.6 187.2,61.8 190.9,65.4
                C194.5,69.0 197.7,73.2 200.1,77.6
                C213.8,80.2 216.3,84.9 216.3,84.9
                C212.7,93.1 206.9,96.0 205.4,96.6
                C205.1,102.4 203.0,107.8 198.3,112.5
                C181.9,128.9 168.3,122.5 157.7,114.1
                C157.9,116.9 156.7,120.9 152.7,124.9
                L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
       fill="currentColor"
       class="octo-body"></path>
     </svg>
   </a>
   <style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
"""

from docutils import nodes


def rcparam_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    """
    Role for matplotlib's rcparams, which are referred to in the documentation via links.
    """
    rendered = nodes.Text('rcParams["{}"]'.format(text))
    refuri = "https://matplotlib.org/api/matplotlib_configuration_api.html#matplotlib.rcParams"
    ref = nodes.reference(rawtext, rendered, refuri=refuri)
    return [nodes.literal("", "", ref)], []


def setup(app):
    app.add_config_value(
        "recommonmark_config",
        {
            "url_resolver": lambda url: github_doc_root + url,
            "auto_toc_tree_section": "Contents",
        },
        True,
    )
    app.add_transform(AutoStructify)
