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

# 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
# sys.path.insert(0, os.path.abspath('.'))
from docutils.parsers.rst import directives
from sphinx.ext.autosummary import Autosummary, get_documenter
from sphinx.util.inspect import safe_getattr

import dpctl

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

project = "Data-parallel Control (dpctl)"
copyright = "2020, Intel Corp."
author = "Intel Corp."

version = dpctl.__version__.strip(".dirty")
# The full version, including alpha/beta/rc tags
release = dpctl.__version__.strip(".dirty")


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

# 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.todo",
    "sphinx.ext.coverage",
    "sphinx.ext.viewcode",
    "sphinx.ext.githubpages",
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.napoleon",
]

todo_include_todos = True
use_doxyrest = "@DPCTL_ENABLE_DOXYREST@"

if use_doxyrest == "ON":
    # Specify the path to Doxyrest extensions for Sphinx:
    import os
    import sys

    sys.path.insert(
        1,
        os.path.abspath("@DOXYREST_SPHINX_DIR@"),
    )
    extensions += ["doxyrest", "cpplexer"]
    # A workaround to fix issues leftover in the doxyrest generated
    # rst files.
    import fileinput

    with fileinput.FileInput(
        "@DOXYREST_OUTPUT_DIR@/global.rst", inplace=True
    ) as file:
        for line in file:
            print(line.replace("typedefDPCTL_C_EXTERN_C_BEGIN", ""), end="")

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

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

highlight_language = "Python"

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

# -- 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"
html_theme_options = {
    "canonical_url": "",
    "analytics_id": "",
    "display_version": True,
    "prev_next_buttons_location": "bottom",
    "style_external_links": False,
    "logo_only": False,
    # Toc options
    "collapse_navigation": True,
    "sticky_navigation": True,
    "navigation_depth": 4,
    "includehidden": True,
    "titles_only": False,
}

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

# When the cmake DPCTL_USE_MULTIVERSION_TEMPLATE flag is set we generate
# links in the sidebar to the documentation for older versions of dpctl.
# Note that ths option does not actually generate the documentation for
# older versions, it only adds links in the sidebar to earlier versions of
# the documentation. All earlier versions of the documentation should be
# generated and pushed to the gh-pages branch manually, after which the
# doc_versions.txt should be updated.

generate_multiversion = "@DPCTL_USE_MULTIVERSION_TEMPLATE@"

if generate_multiversion == "ON":
    try:
        html_context
    except NameError:
        html_context = dict()
    html_context["display_lower_left"] = True
    templates_path = ["_templates"]
    html_context["current_version"] = version
    html_context["version"] = version

    # POPULATE LINKS TO OTHER VERSIONS
    html_context["versions"] = list()

    # Populate the list of documented versions from the doc_versions.tx
    versions = []
    with open("doc_versions.txt", "r") as doc_versions:
        while True:
            version = doc_versions.readline().strip()
            if not version:
                break
            elif len(version):
                versions.append(version)

    # FIXME: Remove this hard coding
    DOC_SITE_NAME = "https://intelpython.github.io/dpctl/"

    for version in versions:
        html_context["versions"].append(
            (version, DOC_SITE_NAME + version + "/index.html")
        )


class AutoAutoSummary(Autosummary):
    """Create a summary for methods and attributes (autosummary).
    See https://stackoverflow.com/questions/20569011/python-sphinx-autosummary-automated-listing-of-member-functions
    """

    option_spec = {
        "methods": directives.unchanged,
        "private_methods": directives.unchanged,
        "attributes": directives.unchanged,
    }

    required_arguments = 1

    @staticmethod
    def get_members(app, obj, typ, include_public=None):
        if not include_public:
            include_public = []
        items = []
        for name in sorted(obj.__dict__.keys()):
            try:
                documenter = get_documenter(app, safe_getattr(obj, name), obj)
            except AttributeError:
                continue
            if documenter.objtype in typ:
                items.append(name)
        return items

    def run(self):
        clazz = str(self.arguments[0])
        (module_name, class_name) = clazz.rsplit(".", 1)
        m = __import__(module_name, globals(), locals(), [class_name])
        c = getattr(m, class_name)
        app = self.state.document.settings.env.app
        if "methods" in self.options:
            methods = self.get_members(app, c, ["method"], ["__init__"])
            self.content = [
                "%s" % method
                for method in methods
                if not method.startswith("_")
            ]
        if "private_methods" in self.options:
            private_methods = self.get_members(app, c, ["method"], ["__init__"])
            self.content = [
                "%s" % method
                for method in private_methods
                if method.startswith("_") and not method.startswith("__")
            ]
        if "attributes" in self.options:
            attribs = self.get_members(app, c, ["attribute", "property"])
            self.content = [
                "%s" % attrib
                for attrib in attribs
                if not attrib.startswith("_")
            ]
        return super().run()


def setup(app):
    app.add_directive("autoautosummary", AutoAutoSummary)
