"""Miscellaneous helper functions and whatnot."""
import logging

import markdown
from flask import current_app as app
from flask import make_response, render_template, request

logger = logging.getLogger(__name__)


def get_meta_str(md, key):
    """Provide the page's (parsed in Markup obj md) metadata for the specified key, or '' if unset."""
    return " ".join(md.Meta.get(key)) if md.Meta.get(key) else ""


def init_md():
    """Initialize the Markdown parser.

    This used to done at the app level in __init__, but extensions like footnotes apparently
    assume the parser to only live for the length of parsing one document, and create double
    footnote ref links if the one parser sees the same document multiple times.
    """
    # initialize markdown parser from config, but include
    # extensions our app depends on, like the meta extension
    return markdown.Markdown(extensions=app.config['MARKDOWN_EXTENSIONS'] + ['meta'],
                             extension_configs=app.config['MARKDOWN_EXTENSION_CONFIGS'])


def render(template_name_or_list, **context):
    """Wrap Flask's render_template.

    * Determine the proper site theme to use in the template and provide it.
    """
    PAGE_STYLES = {
        'dark': 'css/dark.css',
        'light': 'css/light.css',
        'plain': 'css/plain.css',
    }

    selected_style = request.args.get('style', None)
    if selected_style:
        user_style = selected_style
    else:
        user_style = request.cookies.get('user-style')
        logger.debug("user style cookie: %s", user_style)
    context['user_style'] = PAGE_STYLES.get(user_style, PAGE_STYLES.get(app.config['DEFAULT_PAGE_STYLE']))

    resp = make_response(render_template(template_name_or_list, **context))
    if selected_style:
        resp.set_cookie('user-style', selected_style)
    return resp