# -*- coding: iso-8859-1 -*-
"""
MoinMoin weg theme

@copyright: 2003 by RadomirDopieralski (moin@sheep.art.pl)
@license: GNU GPL, see COPYING for details.
"""

from MoinMoin import wikiutil, version
from MoinMoin import caching
from MoinMoin.theme import ThemeBase
from MoinMoin.Page import Page
import StringIO

class Theme(ThemeBase):

    name = "mandarin"

    def header(self, d):
        parts = [
            self.emit_custom_html(self.cfg.page_header1),
            self.msg(d),
            u'<div class="header">',
            self.logo(),
            self.searchform(d),
            self.username(d),
            self.gotobar(d),
            self.editbar(d),
            self.title(d),
            self.logged_trail(d),
            u'</div>',
            self.emit_custom_html(self.cfg.page_header2),
            u'<div class="wrapper">',
            self.sidebar(d),
            u'<div class="content"%s>\n' % self.content_lang_attr(),
        ]
        return u''.join(parts)

    editorheader = header

    def logged_trail(self, d):
        user = self.request.user
        html = u""
        if user.valid and user.show_page_trail:
            if len(user.getTrail())>1:
                html = self.trail(d)
        return html

    def footer(self, d, **keywords):
        page = d['page']
        parts = [
            self.endPage(),
            u'</div></div>',
             self.emit_custom_html(self.cfg.page_footer1),
            u'<div class="footer">',
            self.pageinfo(page),
            u'</div>',
            self.emit_custom_html(self.cfg.page_footer2),
        ]
        return u''.join(parts)

    def sidebar(self, d, **keywords):
        request = self.request
        _ = self.request.getText
        sidebar = 'SideBar';
        page = Page(request, sidebar)
        buff = StringIO.StringIO()
        request.redirect(buff)
        try:
            page.send_page(request, content_only=1, content_id="sidebar")
        finally:
            request.redirect()
        return u'<div class="sidebar">%s</div>' % buff.getvalue()
        

    def editbar(self, d, **keywords):
        if not self.shouldShowEditbar(d['page']):
            return u''
        parts = [
            u'<div class="editbar">',
            self.edit_link(d),
            self.info_link(d),
            self.admin_link(d),
            u'</div>',
        ]
        return u' '.join(parts)

    def edit_link(self, d):
        page = d['page']
        if not (page.isWritable() and
                self.request.user.may.write(page.page_name)):
            return self.login_link(d)
        _ = self.request.getText
        params = (wikiutil.quoteWikinameURL(page.page_name) +
                  '?action=edit')
        text = _('Edit', formatted=False)
        return wikiutil.link_tag(self.request, params, text, css_class="edit")

    def login_link(self, d):
        page = d['page']
        _ = self.request.getText
        params = (wikiutil.quoteWikinameURL(page.page_name) +
                  '?action=login')
        text = _('Locked', formatted=False)
        return wikiutil.link_tag(self.request, params, text, css_class="password")

    def info_link(self, d):
        page = d['page']
        _ = self.request.getText
        params = (wikiutil.quoteWikinameURL(page.page_name) +
                  '?action=info')
        text = _('History', formatted=False)
        return wikiutil.link_tag(self.request, params, text, css_class="history")

    def admin_link(self, d):
        page = d['page']
        _ = self.request.getText
        params = (wikiutil.quoteWikinameURL(page.page_name) +
                  '?action=PageActions')
        text = _('Actions', formatted=False)
        return wikiutil.link_tag(self.request, params, text, css_class="admin")

    def gotobar(self, d, **k):
        request = self.request
        found = {}
        items = []
        item = u'%s'
        current = d['page_name']
        if request.cfg.navi_bar:
            for text in request.cfg.navi_bar:
                #pagename, url = self.splitNaviurl(text)
                pagename, link = self.splitNavilink(text, localize=1)
                if pagename == current:
                    cls = 'wikilink current'
                else:
                    cls = 'wikilink'
                items.append(
                    '<li class="%s">%s</li>'%(cls, link)
                )
                found[pagename] = 1
        userlinks = request.user.getQuickLinks()
        for text in userlinks:
            #pagename, url = self.splitNaviurl(text, localize=0)
            pagename, link = self.splitNavilink(text, localize=0)
            if not pagename in found:
                if pagename == current:
                    cls = 'userlink current'
                else:
                    cls = 'userlink'
                items.append(
                    '<li class="%s">%s</li>' % (cls, link)
                )
                found[pagename] = 1
        return u'<ul class="gotobar">%s<li class="clear"></li></ul>' % u' '.join(items)

    def pagepath(self, d):
        _ = self.request.getText
        content = []
        if d['title_text'] == d['page_name']: # just showing a page, no action
            curpage = u''
            segments = d['page_name'].split('/')
            for s in segments[:-1]:
                curpage += s
                content.append(Page(self.request, curpage).link_to(self.request, s))
                content.append("/")
                curpage += '/'
        html = '<span class="pagepath">%s</span>' % "".join(content)
        return html

    def title(self, d):
        title = d['title_text']
        if title == d['page_name']:
            html = '<h1>%s%s</h1>' % (
                    self.pagepath(d),  wikiutil.escape(title.split('/')[-1]))
        else:
            html = '<h1>%s</h1>' % wikiutil.escape(title)
        return html

    def html_stylesheets(self, d):
        prefix = self.cfg.url_prefix
        url = '%s/%s/%s' % (prefix, self.name, 'style.css')
        return '<link rel="stylesheet" type="text/css" href="%s">' % url

    def searchform(self, d):
        _ = self.request.getText
        form = self.request.form
        updates = {
            'search_label' : _('Search:'),
            'search_value': wikiutil.escape(form.get('value', [''])[0], 1),
            'search_full_label' : _('Text', formatted=False),
            'search_title_label' : _('Titles', formatted=False),
            }
        d.update(updates)

        return u'''
<form class="search" method="get" action="">
<p>
<input type="hidden" name="action" value="fullsearch">
<input type="hidden" name="context" value="180">
<label for="search">%(search_label)s</label>
<input id="search" type="text" name="value" value="%(search_value)s">
<input id="titlesearch" name="titlesearch" type="submit" value="%(search_title_label)s">
<input id="fullsearch" name="fullsearch" type="submit" value="%(search_full_label)s">
</p>
</form>''' % d

    def pageinfo(self, page):
        _ = self.request.getText
        html = ''
        if self.shouldShowPageinfo(page):
            info = page.lastEditInfo()
            if info:
                if info['editor']:
                    info = _("last edited %(time)s by %(editor)s") % info
                else:
                    info = _("last modified %(time)s") % info
                html = '<span class="time"%(lang)s>%(info)s</span>\n' % {
                    'lang': self.ui_lang_attr(),
                    'info': info
                    }
        return html

    def logo(self):
        html = u''
        if self.cfg.logo_string:
            pagename = wikiutil.getFrontPage(self.request).page_name
            pagename = wikiutil.quoteWikinameURL(pagename)
            logo = wikiutil.link_tag(self.request, pagename, self.cfg.logo_string, css_class="logo")
        return logo

    def headscript(self, d):
        return u''

    def externalScript(self, name):
        return u''

    def guiEditorScript(self, d):
        return u''
    def recentchanges_entry(self, d):
        _ = self.request.getText
        if d['comments']:
            rccomm = ''
            for c in d['comments']:
                rccomm += ' <b>%d</b> ' % c[0];
                rccomm += c[1];
        else:
            rccomm = ''
        html = (u'''<li><b class="rctime">%s</b> %s %s . . . . <span class="rcauth">%s</span> <i class="rccomm">%s</i></li>''' % (
            d['time_html'],
            d['pagelink_html'],
            d['icon_html'],
            ', '.join(d['editors']),
            rccomm,
        ))
        return html

    def recentchanges_daybreak(self, d):
        return u'</ul><h3 class="rcdaybreak">%s</h3><ul>' % d['date']

    def recentchanges_header(self, d):
        return u'<div class="recentchanges"%s><ul>' % self.ui_lang_attr()

    def recentchanges_footer(self, d):
        return u'</ul></div>'


def execute(request):
    return Theme(request)

