# -*- coding: utf-8 -*-
# this is being read using exec() by rstgen.sphinxconf.configure()

from pathlib import Path
import rstgen

# from rstgen.sphinxconf import configure ; configure(globals())

docs_root = Path(__file__).parent.absolute()
# print("20210426", docs_root)

# prj = atelier.current_project
# if prj.main_package:
#     root_mod, tpl = srcref_url_template(prj.main_package)
#     if tpl:
#         extlinks.update(srcref=(tpl, ''))

use_dirhtml = rstgen.get_config_var('use_dirhtml')
selectable_languages = rstgen.get_config_var('selectable_languages')

public_url = html_context.setdefault(
    'public_url', rstgen.get_config_var('public_url'))
    # 'public_url', prj.get_public_docs_url('docs'))

def lngfmt(lng):
    return lng.upper()

def get_page_url(language, pagename):
    if use_dirhtml:
        if pagename == master_doc:
            pagename = ""
        elif pagename.endswith("/" + master_doc):
            pagename = pagename[:-len(master_doc)]
    else:
        pagename += ".html"
    if not selectable_languages:
        return pagename
    if language == selectable_languages[0]:
        return pagename
    return language + "/" + pagename

def get_lang_selector(language, pagename, sep=" | "):
    # public_url = prj.get_xconfig('intersphinx_urls')['docs']
    # public_url = prj.get_public_docs_url('docs')
    # public_url = html_context['public_url']
    if not selectable_languages:
        return ''
    if len(selectable_languages) <= 1:
        return ''
    # get_page_url()
    filename = pagename + source_suffix
    if use_dirhtml:
        homename = ""
    else:
        homename = master_doc + source_suffix

    html = ''
    for i, lng in enumerate(selectable_languages):
        if i > 0:
            html += sep
        if lng == language:
            html += "<b>{}</b>".format(lngfmt(lng))
        else:
            href = public_url + "/" + get_page_url(lng, pagename)
            if i == 0:
                pth = docs_root.parent / "docs" / filename
                if not pth.exists():
                    href = homename
            else:
                pth = docs_root.parent / (lng + "docs") / filename
                if not pth.exists():
                    href = lng + "/" + homename
                    # print("Not found b:", pth)
            html += '<a href="{}">{}</a>'.format(href, lngfmt(lng))
    # html += "</p>"
    return html

html_context.update(get_lang_selector=get_lang_selector)
html_context.update(get_page_url=get_page_url)


# extlinks = {}
# extensions = []
# templates_path = []



# extensions += ['sphinxcontrib.youtube']
extensions += ['rstgen.sphinxconf.blog']
extensions += ['rstgen.sphinxconf.complex_tables']
# extensions += ['lino.sphinxcontrib.actordoc']
# extensions += ['sphinxcontrib.taglist']
# extensions += ['sphinx.ext.inheritance_diagram']

# extensions += ['rstgen.sphinxconf.sigal_image']
# sigal_base_url = 'https://sigal.saffre-rumma.net'

# extensions += ['sphinx_panels'] # pip install sphinx-panels
extensions += ['sphinx_design'] # pip install sphinx-design

# source_suffix = '.rst'
# master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'

# 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 = '%d.%B.%Y'

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

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

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

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

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

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

# 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 themes here, relative to this directory.
#html_theme_path = []

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

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = "logo.jpg"

# same logo is being used for all languages
# html_logo = str(Path().absolute() / '../docs/.static/rumma100.png') # pandas

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

# 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".
pth = docs_root / '.static'
if (pth).exists():
    html_static_path.append(str(pth))

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%Y-%m-%d'
#~ 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


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

# If false, no index is generated.
html_use_index = False

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, the reST sources are included in the HTML build as _sources/<name>.
html_copy_source = False

# 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 = ''
# html_use_opensearch = lino.SETUP_INFO['url']

# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''

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

html_css_files = ['atelier.css']

if html_theme == "sphinx_rtd_theme":
    html_theme_options = {
        "prev_next_buttons_location": "both",
        "style_nav_header_background": "#dddddd",
        "style_external_links": False,  # disadvantage: line spacing increases for lines with a link
        "includehidden": False,
    }
    html_sidebars = {
        # '**': ['select_lang.html', 'searchbox.html'],
        '**': ['languages.html', 'globaltoc.html', 'searchbox.html', 'links.html'],
    }
    extensions.append('sphinx_rtd_theme')

elif html_theme == "alabaster":
    my_font_family = "Swiss, Helvetica, 'Liberation Sans'"
    html_theme_options={
        "font_family": my_font_family,
        "head_font_family": my_font_family,
    }
    html_sidebars = {
        # '**': ['select_lang.html', 'searchbox.html'],
        '**': ['globaltoc.html', 'searchbox.html', 'links.html'],
    }
elif html_theme == "pydata_sphinx_theme":
    # https://pydata-sphinx-theme.readthedocs.io/en/latest/user_guide/index.html
    html_theme_options = {
        # "gitlab_url": "https://gitlab.com/saffre-rumma/www",
        "globaltoc_includehidden": True,
        # "collapse_navigation": False,
        "navigation_with_keys": True,
        # "navigation_depth": 2,
        "show_prev_next": False,
        "search_bar_text": "Search...",
        "navbar_center": ["search-field.html"],
        "navbar_end": ["languages.html", "navbar-icon-links.html"],
    }
    panels_add_bootstrap_css = False
    # html_css_files += ["https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"]
    html_sidebars = {
      '**':  [
        # 'languages.html',
        # 'page-toc.html',
        # 'globaltoc.html',
        # 'sidebar-search-bs.html' ,
        'sidebar-nav-bs.html'
        ],
    }
elif html_theme == "insipid":
    html_css_files.append('insipid-cust.css')
    html_theme_options = {
        # 'body_max_width': None,
        # 'breadcrumbs': True,
        'globaltoc_includehidden': False,
        'left_buttons': [
            'search-button.html',
            'home-button.html',
        ],
        'right_buttons': [
            'fullscreen-button.html',
            'repo-button.html',
            'facebook-button.html',
        ],
    }
    html_sidebars = {
        '**' : ['languages.html',
            'globaltoc.html',
            'separator.html',
            'searchbox.html',
            'indices.html',
            'links.html'
            ]}

# intersphinx_mapping = dict(
#     cg=('https://community.lino-framework.org/', None))
