from django.conf import settings
from django.utils.translation import gettext as _
from .help import actionbar as actionbar_add_help
import inspect
import logging
import os
from themes import gray_icon_url, color_icon_url
from users.context import menubar as menubar_user
from users.context import PROFILE_ENTRY_UID
import pygal
from pygal.models import get_item_by_rel_path

logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)


MY_FAVOURITES_ENTRY_UID = 'my_favourites-main'
HELP_UID = 'help-main'
NAVIGATION_ENTRY_UID = 'navigation-main-%s'
HOME_ENTRY_UID = 'home-main'
SEARCH_ENTRY_UID = 'search-main'
BACK_ENTRY_UID = 'back-main'


def context_adaption(context, request, **kwargs):
    caller_name = inspect.currentframe().f_back.f_code.co_name
    wrapper_instance = kwargs.get("wrapper_instance")
    #
    menubar(context, request, **kwargs)
    navigationbar(context, request, **kwargs)
    if wrapper_instance is None:
        # Pages without direct connection to an item (e.g. Helpview, ...)
        context.set_additional_title(kwargs.get("title", ""))
        #
        actionbar(context, request, caller_name)
    else:
        wrapper_instance.context_adaption(context)
    # HELP
    if pygal.is_helpview(request):
        actionbar_add_help(context, request, current_help_page=kwargs.get("current_help_page"))
    for key in kwargs:
        context[key] = kwargs[key]
    logger.debug("context adapted: %s", repr(context))

def navigationbar(context, request, **kwargs):
    bar = context[context.NAVIGATIONBAR]
    rel_path = kwargs.get("rel_path", '')
    #
    if pygal.is_favouriteview(request):
        if rel_path:
            bar.append_entry(*navigation_entry_parameters(request, rel_path, None))
            anchor = get_item_by_rel_path(rel_path).name
        else:
            anchor = None
    elif pygal.is_searchview(request):
        if rel_path:
            bar.append_entry(*navigation_entry_parameters(request, rel_path, None))
            anchor = get_item_by_rel_path(rel_path).name
        else:
            anchor = None
    else:
        anchor = None
        while len(rel_path) > 0 and rel_path != os.path.sep:
            bar.append_entry(*navigation_entry_parameters(request, rel_path, anchor))
            anchor = get_item_by_rel_path(rel_path).name
            rel_path = os.path.dirname(rel_path)
    bar.append_entry(*home_entry_parameters(request, anchor))


def menubar(context, request, **kwargs):
    bar = context[context.MENUBAR]
    rel_path = kwargs.get("rel_path", '')
    #
    bar.append_entry(HELP_UID, _('Help'), color_icon_url(request, 'help.png'), pygal.url_helpview(request, 'main'), True, False)
    menubar_user(bar, request)
    if request.user.is_authenticated:
        bar.append_entry(*my_favourites_entry_parameters(request, rel_path))
    try:
        bar.replace_entry(PROFILE_ENTRY_UID, *profile_entry_parameters(request))
    except ValueError:
        pass        # Profile entry does not exist, so exchange is not needed (e.g. no user is logged in)


def actionbar(context, request, caller_name, **kwargs):
    bar = context[context.ACTIONBAR]
    bar.append_entry(
        BACK_ENTRY_UID,                             # uid
        _('Back'),                                  # name
        color_icon_url(request, 'back.png'),        # icon
        'javascript:history.back()',                # url
        True,                                       # left
        False                                       # active
    )

def profile_entry_parameters(request):
    return (
        PROFILE_ENTRY_UID,                          # uid
        request.user.username,                      # name
        color_icon_url(request, 'user.png'),        # icon
        pygal.url_profile(request),                 # url
        False,                                      # left
        False                                       # active
    )


def home_entry_parameters(request, anchor=None):
    if pygal.is_favouriteview(request):
        icon = 'favourite.png'
    elif pygal.is_searchview(request):
        icon = 'search.png'
    else:
        icon = 'home.png'
    return (
        HOME_ENTRY_UID,
        ':',
        gray_icon_url(request, icon),
        pygal.url_userview(request, rel_path='', search=pygal.SEARCH_KEEP) + ('#%s' % anchor if anchor is not None else ''),
        True,
        False
    )


def search_entry_parameters(request):
    return (
        SEARCH_ENTRY_UID,
        ':',
        gray_icon_url(request, 'search.png'),
        pygal.url_search(request),
        True,
        False
    )


def navigation_entry_parameters(request, path, anchor=None):
    return (
        NAVIGATION_ENTRY_UID % os.path.basename(path),                                                                  # uid
        '/' + os.path.basename(path),                                                                                   # name
        None,                                                                                                           # icon
        pygal.url_userview(request, path, search=pygal.SEARCH_KEEP) + ('#%s' % anchor if anchor is not None else ''),   # url
        False,                                                                                                          # left
        False                                                                                                           # active
    )


def my_favourites_entry_parameters(request, rel_path):
    if pygal.is_favouriteview(request) and rel_path != '':
        url_addon = '#%s' % get_item_by_rel_path(rel_path).name
    else:
        url_addon = ''
    return (
        MY_FAVOURITES_ENTRY_UID,                        # uid
        _('My Favourites'),                             # name
        color_icon_url(request, 'favourite.png'),       # icon
        pygal.url_favouriteview(request) + url_addon,   # url
        True,                                           # left
        pygal.is_favouriteview(request)                 # active
    )

