from quixote import get_request, get_publisher, get_response
from qommon.publisher import get_publisher_class
from quixote.html import htmltext

from wcs.qommon import _
from wcs.qommon import template
from wcs.qommon.admin.texts import TextsDirectory
from wcs.categories import Category

wcs_error_page = template.error_page
wcs_get_decorate_vars = template.get_decorate_vars

def get_decorate_vars(body, response, generate_breadcrumb=True, template_context=None, **kwargs):
    if template_context and 'form_side' in template_context:
        # force rendering as it will put new variables in the context
        template_context['form_side'] = template_context['form_side']()

    for key in ('bigdiv', 'gauche'):
        if not response.filter.has_key(key):
            response.filter[key] = None

    return wcs_get_decorate_vars(body, response, generate_breadcrumb)


def render_response(publisher, body):
    response = get_response()

    if isinstance(body, template.QommonTemplateResponse):
        body = template.render(body.templates, body.context)
    body = str(body)

    root_url = publisher.get_root_url()
    wcs_path = publisher.get_request().get_path()[len(root_url):]
    section = wcs_path.split('/')[0]

    if section in ('backoffice', 'admin'):
        return template.decorate(body, response)

    section_title = ''
    page_title = response.filter.get('title')
    if 'error-page' in response.filter:
        pass
    elif section == 'consultations':
        section_title = '<h2 id="consultations">%s</h2>\n' % _('Consultations')
        response.filter['bigdiv'] = 'rub_consultation'
    elif section == 'announces':
        response.filter['bigdiv'] = 'rub_annonce'
        section_title = '<h2 id="announces">%s</h2>\n' % _('Announces to citizens')
        if page_title == _('Announces to citizens'):
            page_title = ''
    elif section == 'agenda':
        response.filter['bigdiv'] = 'rub_agenda'
        section_title = '<h2 id="agenda">%s</h2>\n' % _('Agenda')
        if page_title == _('Agenda'):
            page_title = ''
    elif section and len(section) > 1:
        # XXX: this works but is not efficient
        if Category.has_urlname(section):
            section_title = '<h2 id="services">%s</h2>\n' % _('Services')
            response.filter['bigdiv'] = 'rub_service'

    if not 'auquotidien-no-titles-in-section' in response.filter.get('keywords', []):
        if page_title:
            if section_title:
                page_title = '<h3>%s</h3>' % page_title
            else:
                page_title = '<h2 id="info">%s</h2>' % page_title
        else:
            page_title = ''

        body = '\n'.join((section_title, page_title, body))

    if hasattr(response, 'breadcrumb') and response.breadcrumb:
        if len(response.breadcrumb) == 1:
            response.breadcrumb = None

    return template.decorate(body, response)


def error_page(*args, **kwargs):
    get_response().filter = {}
    get_response().filter['error-page'] = None
    get_response().filter['keywords'] = template.get_current_theme().get('keywords')
    get_response().filter['title'] = template.get_current_theme().get('keywords')
    get_response().filter['gauche'] = TextsDirectory.get_html_text('aq-error-assistance')
    error_page = wcs_error_page(*args, **kwargs)
    title = get_response().filter['title']
    get_response().filter['title'] = None
    return htmltext('<div id="info"><h2>%s</h2>' % title) + error_page + htmltext('</div>')

template.error_page = error_page
template.get_decorate_vars = get_decorate_vars
get_publisher_class().render_response = render_response

TextsDirectory.register('aq-error-assistance', N_('Assistance text next to errors'))
