from cStringIO import StringIO
import os

from quixote import get_session, get_request, get_response, get_publisher
import ezt

import misc
from users import User
from hosts import Host

DEFAULT_TEMPLATE_EZT = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>[page_title]</title>
    <link rel="stylesheet" type="text/css" href="[css]"/>
    [script]
  </head>
  <body[if-any onload] onload="[onload]"[end][if-any body_class] class="[body_class]"[end]>
    <div id="page">
    <div id="top"> <h1>[if-any title][title][else][org_name][end]</h1> </div>
    <div id="main-content">
    [prelude]
    [if-any breadcrumb]<p id="breadcrumb">[breadcrumb]</p>[end]
    [body]
    </div>
    <div id="footer"><p id="lasso">Powered by Lasso</p></div>
    </div>
  </body>
</html>"""

ADMIN_TEMPLATE_EZT = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>[page_title]</title>
    <link rel="stylesheet" type="text/css" href="[css]"/>
    [script]
  </head>
  <body>
  <div id="header">[header_menu]</div>
  <div id="main-content">
    [user_info]
    [if-any breadcrumb]
    <p id="breadcrumb">[breadcrumb]</p>
    [end]
    <h1>[subtitle]</h1>

    [body]

  </div>
  <div id="footer">
   <p id="lasso">Powered by Lasso</p>
  </div>
 </body>
</html>"""


default_template = ezt.Template()
default_template.parse(DEFAULT_TEMPLATE_EZT)

admin_template = ezt.Template()
admin_template.parse(ADMIN_TEMPLATE_EZT)


def html_top(title = None, onload = None, script = None, default_org = 'WCS',
        force_ignore_user = False):
    get_response().filter.update(locals())


def error_page [html] (error_message, error_title = None, exception = None):
    if not error_title:
        error_title = _('Error')
    script = None
    if exception:
        scripts = ['/js/prototype.js', '/js/scriptaculous/scriptaculous.js']
        script = '\n'.join(
                ['<script src="%s" type="text/javascript"></script>' % x for x in scripts])

    html_top(error_title, script = script)
    '<div class="error-page">'
    '<p>%s</p>' % error_message
    if exception and get_publisher().logger.error_email:
        '<p>%s</p>' % _('It has been sent to the site administrator for analyse.')
    if exception:
        '''<p><a href="#" onclick="new Effect.SlideDown('exception'); '''
        '''this.style.display = 'none'; return false;">%s</a></p>''' % _('View Error Details')
        '<pre id="exception" style="display: none;"><code>%s</code></pre>' % exception
    '</div>'


def decorate(body, response):
    if response.filter.get('no_template'):
        return body    
    body = str(body)
    kwargs = {}
    for k, v in response.filter.items():
        if v:
            kwargs[k] = str(v)
    onload = kwargs.get('onload')
    body_class = kwargs.get('body_class')

    org_name = None
    host = Host.get_host_from_url()
    if host is not None:
        org_name = host.organization_name

    current_theme = misc.cfg.get('branding', {}).get('theme', 'default')
    include_user = misc.cfg.get('misc', {}).get('include-user-details', False)
    if kwargs.get('title'):
        title = kwargs.get('title')
        if org_name is not None:
            page_title = '%s - %s' % (org_name, title)
        else:
            page_title = '%s' % title
        title_or_orgname = title
    else:
        page_title = org_name
        title = None
        title_or_orgname = org_name
    script = kwargs.get('script') or ''

    if response.filter.get('admin_ezt'):
        header_menu = kwargs.get('header_menu')
        user_info = kwargs.get('user_info')
        page_title = kwargs.get('sitetitle') + kwargs.get('title', '')
        subtitle = kwargs.get('subtitle')
        css = get_request().environ['SCRIPT_NAME'] + '/larpe/css/dc2/larpe-admin.css'
        script = kwargs.get('scripts')
        generate_breadcrumb = True
        template = admin_template
    else:
        if current_theme == 'default':
            css = '/larpe/css/larpe.css'
        else:
            css = '/larpe/themes/%s/larpe.css' % current_theme

        prelude = ''
        if include_user and not kwargs.get('force_ignore_user'):
            session = get_session()
            if session and session.user and not str(session.user).startswith(str('anonymous-')):
                try:
                    user = User.get(session.user)
                except (KeyError, ValueError):
                    pass
                else:
                    prelude = '<p id="prelude">%s</p>' % (_('Logged in as %s.') % user.name)



        template_ezt = misc.cfg.get('branding', {}).get('template')
        if not template_ezt:
            # the theme can provider a default template
            filename = os.path.join(get_publisher().data_dir, 'themes', current_theme, 'template.ezt')
            if os.path.exists(filename):
                template_ezt = file(filename).read()
        if template_ezt:
            generate_breadcrumb = ('[breadcrumb]' in template_ezt)
            template = ezt.Template()
            template.parse(template_ezt)
        else:
            generate_breadcrumb = True
            template = default_template

    if generate_breadcrumb:
        breadcrumb = ''
        if hasattr(response, 'breadcrumb') and response.breadcrumb:
            s = []
            path = get_request().environ['SCRIPT_NAME'] + '/'
            for component, label in response.breadcrumb:
                if component.startswith('http'):
                    s.append('<a href="%s">%s</a>' % (component, label))
                    continue
                s.append('<a href="%s%s">%s</a>' % (path, component, label))
                path += component
            breadcrumb = ' > '.join(s)

    fd = StringIO()
    template.generate(fd, locals())
    return fd.getvalue()
