# -*- coding: utf-8 -*-
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# %                                                         PyXMake - Custom input filter script for Sphinx with custom schemes                            %
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
"""
Configuration file for Sphinx used during preprocessing

@note: PyXMake's configuration file for Sphinx.
Created on 05.08.2020

@version:  1.0    
----------------------------------------------------------------------------------------------
@requires:
       - 

@change: 
       -

@author: garb_ma                                                                         [DLR-SY,STM Braunschweig]
----------------------------------------------------------------------------------------------
"""

## @namespace PyXMake.Build.config.stm_conf
# Configuration file for Sphinx used during preprocessing.
## @author 
# Marc Garbade
## @date
# 05.08.2020
## @par Notes/Changes
# - Added documentation // mg 05.08.2020

# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import os
import sys
import datetime

try: import sphinx_rtd_theme #@UnusedImport
except: pass

try: from importlib.util import find_spec as check
except ImportError: from pkgutil import find_loader as check #@UnusedImport @Reimport

from sphinx.ext.autodoc import between #@UnresolvedImport

# -- 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.dirname(__file__))

# Loop over all provided paths to allow relative imports
for item in os.environ['sphinx_include'].split(os.pathsep):
    sys.path.insert(0,item)

# -- Project information -----------------------------------------------------
# General information about the project.
project = os.getenv("sphinx_project",'Structural Mechanics Lab')
author = os.getenv("sphinx_author",'German Aerospace Center - Institute of Lightweight Systems')
now = datetime.datetime.now()
copyright = str(now.year)+', %s' % author #@ReservedAssignment

# -- General configuration ---------------------------------------------------
# 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 = 'en'

# 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', 'Thumbs.db', '.DS_Store']

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

# 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.viewcode', # extension to include source code
              'sphinx.ext.todo',
              'sphinx.ext.autodoc',
              'sphinx.ext.graphviz', 'sphinx.ext.inheritance_diagram',
              'sphinx.ext.autosummary',
              'sphinx.ext.autosectionlabel',
              'sphinxcontrib.bibtex',
              'autodocsumm',
              ]
 
extensions += ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.napoleon']
extensions += [x for x in ["sphinx_design", "sphinx_favicon",'sphinxcontrib.openapi','sphinxcontrib.redoc'] if check(x) is not None]

try: 
    from myst_parser import parsers as _ #@UnusedImport @UnresolvedImport @Reimport
    extensions += ['myst_parser']
    myst_enable_extensions = ["colon_fence"]
except:
    try: 
        from recommonmark.transform import AutoStructify as _ #@Reimport @UnusedImport 
        extensions += ["recommonmark"]
    except: pass

try: 
    import sphinxemoji as _ #@UnusedImport @Reimport
    extensions += ['sphinxemoji.sphinxemoji']
    sphinxemoji_style = 'twemoji'
except: pass

# Approach to render equations in HTML outputs. Defaults to MathJax - which requires an active internet connection.
if not os.getenv("sphinx_render_equations"):
    extensions += ["sphinx.ext.mathjax"]
else:
    extensions +=  ["sphinx.ext.imgmath"]

# The suffix of source filenames.
source_suffix = {
    '.rst': 'restructuredtext',
    '.md': 'markdown',
}

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

# The master toctree document.
master_doc = os.getenv("sphinx_master","index")

# 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 = [os.getenv("sphinx_static","_static")]
html_search_language = 'en'

# HTML theme
html_theme = os.getenv("sphinx_html_theme",'sphinx_rtd_theme')

extensions += [html_theme]

# MathJax path
mathjax_path = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"

# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["/".join([".",os.getenv("sphinx_templates","_templates")])]

# Html logo in navbar.
# Fit in the navbar at the height of image is 37 px.
html_logo = os.getenv("sphinx_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.
if os.getenv("sphinx_favicon",None): os.environ["html_favicon"] = os.getenv("sphinx_favicon",None)

# HTML theme options
html_theme_options = {
    # 'canonical_url': '',
    # 'analytics_id': 'UA-XXXXXXX-1',  #  Provided by Google in your dashboard
    'logo_only': False,
    'display_version': True,
    'prev_next_buttons_location': 'tob',
    'style_external_links': True,
    # 'vcs_pageview_mode': '',
    'style_nav_header_background': os.getenv("sphinx_color","blue"),
    # Toc options
    'collapse_navigation': True,
    'sticky_navigation': True,
    'navigation_depth': 4,
    'includehidden': False,
    'titles_only': False
}

# HTML context options
html_context = {
"display_gitlab": True, # Add 'Edit on Github' link instead of 'View page source'
"last_updated": True,
"commit": False,
}

# If true, links to the reST sources are added to the pages. Mutually exclusive with custom-set GitLab link.
html_show_sourcelink = False if html_theme in ['sphinx_rtd_theme'] else True

# Modify footer section when using this theme
if html_theme in ["pydata_sphinx_theme"]:
    # Delete unsupported options
    current_keys = list(html_theme_options.keys())
    _ = [html_theme_options.pop(x) for x in current_keys if x not in ["navigation_depth","collapse_navigation"]]
    # Update HTML theme options
    html_theme_options.update({"footer_start": ["copyright"],
                           "footer_center": ["sphinx-version"],
                           "footer_end": ["theme-version"]})
    html_theme_options.update({"icon_links_label": "Quick Links"})
    # Added logo definition
    html_theme_options.update({"logo": {"text": "%s" % project}})
    # Reuse the same logo for both icon and logo
    if os.path.exists(html_logo) and os.path.splitext(html_logo)[-1] in [".ico"]: html_favicon = html_logo

#=======================================================================================================================
# inheritance_diagram_custom attributes
#=======================================================================================================================
#inheritance graph attributes
inheritance_graph_attrs = dict(rankdir="TB", size='""', fontsize=14, ratio='compress')
inheritance_node_attrs = dict(shape='record', fontsize=16, style='filled') 

# dot output format ['svg'|'png']
graphviz_output_format = 'svg'

bibtex_bibfiles = ['_about/references.bib']

#=======================================================================================================================
# autoclass options
#=======================================================================================================================
# # generate autosummary pages
# autosummary_generate=True

# http://sphinx.pocoo.org/ext/autodoc.html#confval-autoclass_content
#autoclass_content = 'both'

#order of modules and class members
autodoc_member_order = 'bysource'

#autodoc flags that can be switched on for everything
# to switch of us this:
#.. automodule:: foo
#   :no-show-inheritance:
autodoc_default_options = {
    'autosummary': True,
    'members': True,
    'no-inherited-members':True,
    'member-order': 'bysource',
    'show-inheritance': True,
}
#This value contains a list of modules to be mocked up. 
#This is useful when some external dependencies are not met at build time and break the building process
autodoc_mock_imports = ['django']

#=======================================================================================================================
# autosectionlabel options
#=======================================================================================================================
autosectionlabel_prefix_document = True

def setup(app):
    # Register a sphinx.ext.autodoc.between listener to ignore everything
    # between lines that contain the word IGNORE
    app.connect('autodoc-process-docstring', between('^.*@.*$', exclude=True))
    app.connect('autodoc-process-docstring', between('^.*-----------------------.*$', exclude=True))
    return app