# -*- 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, sys, json, shutil, datetime, configparser, re, subprocess

root_dir = os.path.abspath(
    os.path.join(
        '..',
        '..'
    )
)

sys.path.insert(0, os.path.join(root_dir, 'src' ) )


def get_setup_cfg():
    cfg_filename = os.path.join(root_dir, 'setup.cfg')
    with open(cfg_filename, 'r') as filp:
        cfg = configparser.ConfigParser()
        cfg.read_file(filp, source=cfg_filename)
        return dict(
            ( section, dict( cfg.items(section) ) )
            for section
            in  cfg.sections()
        )

# -- Project information -----------------------------------------------------
setup_cfg = get_setup_cfg()
now       = datetime.datetime.utcnow()
metadata  = setup_cfg["metadata"]
project   = metadata["name"]
author    = metadata["author"]
copyright = "%s, %s" % (now.year, metadata["author"])
version   = u''
release   = u''

# -- 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.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',

    #'sphinxcontrib.apidoc', < tricky getting this to do what i want.>
    'sphinxcontrib.openapi',
    #'sphinxcontrib.blockdiag', < doesn't seem to work anymore
    'sphinx_automodapi.automodapi',
    'numpydoc'
]

#apidoc_module_dir     = '../../src/pt/ptutils'
#apidoc_excluded_paths = []
#apidoc_output_dir     = 'api'

# 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 = 'alabaster'

# 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 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.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself.  Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}


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

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


# -- 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, 'ptutils.tex', u'Principled Technologies Boilerplate Utilities Documentation',
     u'Christopher Wolfe', '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, 'ptutils', u'Principled Technologies Boilerplate Utilities 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, 'ptutils', u'Principled Technologies Boilerplate Utilities Documentation',
     author, 'ptutils', 'A repository of oft used functions and utility classes.',
     'Miscellaneous'),
]


# -- 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.
intersphinx_mapping = {'https://docs.python.org/': None}

# -- Options for todo extension ----------------------------------------------

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

#===========================================================================
# Options for sphinx_rtd_theme
#===========================================================================
# https://github.com/rtfd/sphinx_rtd_theme
# https://sphinx-rtd-theme.readthedocs.io/en/latest/configuring.html
# https://docs.readthedocs.io/en/latest/guides/adding-custom-css.html
html_theme = "sphinx_rtd_theme"
html_logo  = '.static/img/logo.png'
html_theme_options = {
    'canonical_url':                '',
    'logo_only':                    False,
    'display_version':              True,
    'prev_next_buttons_location':   'bottom',
    'style_external_links':         True,
    # Toc options
    'collapse_navigation':          True,
    'sticky_navigation':            True,
    'navigation_depth':             4,
    'includehidden':                True,
    'titles_only':                  False
}

#===========================================================================
# Options for automodapi
#===========================================================================
# https://sphinx-automodapi.readthedocs.io/en/latest/automodapi.html
automodapi_inheritance_diagram = False
automodapi_toctreedirnm        = 'api'
automodapi_writereprocessed    = False
automodsumm_inherited_members  = True
autosummary_generate           = True
# autosummary_imported_members   = True

#===========================================================================
# Options for NumPyDoc
#===========================================================================
# Note: this is required to be false by automodapi to prevent duplicating
# documentation.
numpydoc_show_class_members    = False
suppress_warnings = ['toc.secnum']

############################################################################
# Utility functions
############################################################################
from json import JSONEncoder

def default_json_encoder(obj):
    try:
        return obj.__dict__
    except:
        pass
    try:
        return magic(obj)
    except:
        pass

    return repr(obj)

def pretty(obj):
    """Return a human-friendly JSON representation of an object (must be JSON-serializable)."""
    return json.dumps(obj, indent=2, sort_keys=True, default=default_json_encoder)

def have_dot():
    """Test if GraphViz's 'dot' program is installed."""
    rv = shutil.which("dot") is not None
    if not rv:
        print("NOTICE: Graphviz does not appear to be installed (could not find 'dot' executable), inheritance diagram generation is disabled.")
    return rv

def native_path(upath):
    return upath.replace('/', os.path.sep)

#===========================================================================
# plug-in to add template processing to rst documents
#===========================================================================
# from https://www.ericholscher.com/blog/2016/jul/25/integrating-jinja-rst-sphinx/
def source_template_preprocessor(app, docname, source):
    """
    Render our pages as a jinja template for fancy templating goodness.
    """
    # Make sure we're outputting HTML
    if app.builder.format != 'html':
        return

    if docname.startswith('api'+os.sep):
        return

    source[0] = app.builder.templates.render_string(
        source[0], vars(app.config)
    )


#===========================================================================
# Main set-up function
#===========================================================================
def setup(app):

    # make custom styles available
    app.add_css_file('css/pt-sphinx-rtd-theme.css')

    # connect the template preprocessor
    app.connect("source-read", source_template_preprocessor)

    # adjust dynamic options
    app.config.automodapi_inheritance_diagram = have_dot()

    try:
        repository_url = subprocess.check_output(['git', 'config', 'remote.origin.url']).strip().decode('utf-8')
        m = re.match(r'^(?:.*/)?([^/]+)', repository_url)
        if m:
            repository_name = m.group(1)
            if repository_name.endswith('.git'):
                repository_name = repository_name[:-4]

        app.config.repository_url = repository_url
        app.config.repository_name = repository_name

    except Exception as e:
        print("WARNING: unable to determine GIT repository URL: %s" %e)

    have_openapi     = False
    openapi_fullpath = None
    openapi_relpath  = None
    try:
        openapi_file = setup_cfg.get("miscellaneous", dict()).get("openapi_file", None)
        if openapi_file:
            fullpath = os.path.join(root_dir, native_path(openapi_file))
            have_openapi = os.path.exists( fullpath )
            if have_openapi:
                openapi_fullpath = fullpath
                openapi_relpath  = os.path.relpath(openapi_fullpath, os.path.abspath(os.path.join('.', 'doc', 'source' )))
    except:
        pass
    print("openapi_fullpath - %s" % openapi_fullpath)
    print("openapi_relpath  - %s" % openapi_relpath)
    print("have_openapi     - %s" % have_openapi)
    app.config.have_openapi     = have_openapi
    app.config.openapi_fullpath = openapi_fullpath
    app.config.openapi_relpath  = openapi_relpath



    app.config.docs_build_date  = now
    app.config.setup_cfg        = setup_cfg
    app.config.author           = setup_cfg["metadata"]["author"]
    app.config.copyright        = u"%s, %s" % (now.year, app.config.author)






#print(globals())
