# -*- coding: iso-8859-1 -*-
"""
    MoinMoin clean theme
    
    based on MoinMoin classic theme

    @copyright: 2005 by Radomir Dopieralski (moin@sheep.prv.pl)
    @license: GNU GPL, see COPYING for details.
"""

from MoinMoin import i18n, wikiutil, version
from MoinMoin.theme import ThemeBase
from MoinMoin.Page import Page


class Theme(ThemeBase):
    """ here are the functions generating the html responsible for
        the look and feel of your wiki site
    """
    
    name = "clean"

    # fake _ function to get gettext recognize those texts:
    _ = lambda x: x

    # TODO: remove icons that are not used any more.
    icons = {
        # key         alt                        icon filename      w   h
        # ------------------------------------------------------------------
        # navibar
        'help':       ("%(page_help_contents)s", "moin-help.png",   12, 11),
        'find':       ("%(page_find_page)s",     "moin-search.png", 12, 12),
        'diff':       (_("Diffs"),               "moin-diff.gif",   24, 24),
        'info':       (_("Info"),                "moin-info.gif",   24, 24),
        'edit':       (_("Edit"),                "moin-edit.gif",   24, 24),
        'unsubscribe':(_("Unsubscribe"),         "moin-unsubscribe.gif",  24, 24),
        'subscribe':  (_("Subscribe"),           "moin-subscribe.gif", 24, 24),
        'raw':        (_("Raw"),                 "moin-raw.gif",    24, 24),
        'xml':        (_("XML"),                 "moin-xml.png",    20, 13),
        'print':      (_("Print"),               "moin-print.gif",  24, 24),
        'delete':     (_("Delete"),              "moin-delete.gif", 24, 24),
        'view':       (_("View"),                "moin-show.gif",   24, 24),
        'home':       (_("Home"),                "moin-home.png",   24, 24),
        'up':         (_("Up"),                  "moin-parent.gif", 24, 24),
        # FileAttach
        'attach':     ("%(attach_count)s",       "moin-attach.gif",  24, 24),
        # RecentChanges
        'rss':        (_("[RSS]"),               "moin-rss.png",    36, 14),
        'deleted':    (_("[DELETED]"),           "moin-deleted.png",60, 12),
        'updated':    (_("[UPDATED]"),           "moin-updated.png",60, 12),
        'new':        (_("[NEW]"),               "moin-new.png",    31, 12),
        'diffrc':     (_("[DIFF]"),              "moin-diff.png",   15, 11),
        # General
        'bottom':     (_("[BOTTOM]"),            "moin-bottom.png", 14, 10),
        'top':        (_("[TOP]"),               "moin-top.png",    14, 10),
        'www':        ("[WWW]",                  "moin-www.png",    11, 11),
        'mailto':     ("[MAILTO]",               "moin-email.png",  14, 10),
        'news':       ("[NEWS]",                 "moin-news.png",   10, 11),
        'telnet':     ("[TELNET]",               "moin-telnet.png", 10, 11),
        'ftp':        ("[FTP]",                  "moin-ftp.png",    11, 11),
        'file':       ("[FILE]",                 "moin-ftp.png",    11, 11),
        # search forms
        'searchbutton': ("[?]",                  "moin-search.png", 12, 12),
        'interwiki':  ("[%(wikitag)s]",          "moin-inter.png",  16, 16),
    }
    del _

    def iconbar(self, d):
        """
        Assemble the iconbar
        
        @param d: parameter dictionary
        @rtype: string
        @return: iconbar html
        """
        iconbar = []
        if self.cfg.page_iconbar and self.request.user.show_toolbar and d['page_name']:
            iconbar.append('<ul id="iconbar">\n')
            icons = self.cfg.page_iconbar[:]
            for icon in icons:
                if icon == "up":
                    if d['page_parent_page']:
                       iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
                elif icon == "delete":
                    if d['page'].isWritable() and self.request.user.may.delete(d['page_name']):
                        iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
                elif icon == "attach":
                    if d['page'].isWritable() and self.request.user.may.write(d['page_name']):
                        iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
                elif icon == "edit":
                    if d['page'].isWritable() and self.request.user.may.write(d['page_name']):
                        iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
                elif icon == "subscribe":
                    if self.cfg.mail_smarthost and self.request.user.email:
                        iconbar.append('<li>%s</li>\n' % self.make_iconlink(
                            ["subscribe", "unsubscribe"][self.request.user.isSubscribedTo([d['page_name']])], d))
                elif icon == "home":
                    if d['page_home_page']:
                        iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
                else:
                    iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d))
            iconbar.append('</ul>\n')
        return ''.join(iconbar)
    
    def header(self, d, **keywords):
        """
        Assemble page header
        
        @param d: parameter dictionary
        @rtype: string
        @return: page header html
        """
        dict = {
            'config_header1_html': self.emit_custom_html(self.cfg.page_header1),
            'config_header2_html': self.emit_custom_html(self.cfg.page_header2),
            'search_form_html': self.searchform(d),
            'logo_html':  self.logo(),
            'username_html':  self.username(d),
            'navibar_html': self.navibar(d),
            'iconbar_html': self.iconbar(d),
            'msg_html': self.msg(d),
            'trail_html': self.trail(d),
            'startpage_html': self.startPage(),
            'title_html':  self.title(d),
            'available_actions_html': self.availableactions(d),
            'credits_html': self.credits(d, **keywords),
            'version_html': self.showversion(d, **keywords),
        }
        dict.update(d)

        html = """
%(config_header1_html)s
%(msg_html)s
<div id="menu">
%(logo_html)s
%(iconbar_html)s
%(search_form_html)s
%(navibar_html)s
%(trail_html)s
%(username_html)s
%(available_actions_html)s
%(credits_html)s
%(version_html)s
</div>
<div id="container">
%(config_header2_html)s
%(startpage_html)s
%(title_html)s
""" % dict
        return html

    # Footer stuff #######################################################
    
    def edittext_link(self, d, **keywords):
        """
        Assemble EditText link (or indication that page cannot be edited)
        
        @param d: parameter dictionary
        @rtype: string
        @return: edittext link html
        """
        _ = self.request.getText
        page = d['page']
        if keywords.get('editable', 1):

            # Add edit link
            editable = (self.request.user.may.write(d['page_name']) and
                        page.isWritable())
            if editable:
                title = _('EditText', formatted=False)
                edit = wikiutil.link_tag(self.request, d['q_page_name'] +
                                         '?action=edit', title)
            else:
                edit = _('Immutable page')

            # Add last edit info
            info = page.lastEditInfo()
            if info:
                if info.get('editor'):
                    info = _("last edited %(time)s by %(editor)s") % info
                else:
                    info = _("last modified %(time)s") % info
                return '<p>%s (%s)</p>' % (edit, info)
        return ''

    def footer_fragments(self, d, **keywords):
        """
        assemble HTML code fragments added by the page formatters
        
        @param d: parameter dictionary
        @rtype: string
        @return: footer fragments html
        """
        html = ''
        if d['footer_fragments']:
            html = ''.join(d['footer_fragments'].values())
        return html
    def username(self, d):
        """ Assemble the username / userprefs link
        
        @param d: parameter dictionary
        @rtype: unicode
        @return: username html
        """
        request = self.request
        _ = request.getText
        preferencesPage = wikiutil.getSysPage(request, _('UserPreferences', formatted=False))

        # XXX for some reason sometimes there's no fromatter in the request :/
	try:
		formatter = request.formatter
	except:
		formatter = None
        
        userlinks = []
        # Add username/homepage link for registered users. We don't care
        # if it exists, the user can create it.
        if request.user.valid:
            homepage = Page(request, request.user.name)
            title = homepage.split_title(request)
            homelink = homepage.link_to(request, text=title)
            userlinks.append(homelink)
            # Set pref page to localized Preferences page
            title = preferencesPage.split_title(request)
            userlinks.append(preferencesPage.link_to(request, text=title))
            # add a lgout option
            if formatter:
                userlinks.append(preferencesPage.link_to(request, text=_('Logout'), querystr='action=userform&logout'))
        else:
            # Add prefpage links with title: Login
            userlinks.append(preferencesPage.link_to(request, text=_("Login")))
            
        userlinks = [u'<li>%s</li>' % link for link in userlinks]
        html = u'<ul id="username">%s</ul>' % ''.join(userlinks)
        return html


    # Override this class just to remove the newlines at the ends of </li>, because IE doesn't like them
    def navibar(self, d):
        """ Assemble the navibar

        @param d: parameter dictionary
        @rtype: unicode
        @return: navibar html
        """
        request = self.request
        found = {} # pages we found. prevent duplicates
        items = [] # navibar items
        item = u'<li class="%s">%s</li>'
        current = d['page_name']

        # Process config navi_bar
        if request.cfg.navi_bar:
            for text in request.cfg.navi_bar:
                pagename, link = self.splitNavilink(text)
                cls = 'wikilink'
                if pagename == current:
                    cls = 'wikilink current'
                items.append(item % (cls, link))
                found[pagename] = 1

        # Add user links to wiki links, eliminating duplicates.
        userlinks = request.user.getQuickLinks()
        for text in userlinks:
            # Split text without localization, user know what she wants
            pagename, link = self.splitNavilink(text, localize=0)
            if not pagename in found:
                cls = 'userlink'
                if pagename == current:
                    cls = 'userlink current'
                items.append(item % (cls, link))
                found[pagename] = 1

        # Add current page at end
        if not current in found:
            title = d['page'].split_title(request)
            title = self.shortenPagename(title)
            link = d['page'].link_to(request, title)
            cls = 'current'
            items.append(item % (cls, link))

        # Assemble html
        items = u''.join(items)
        html = u''' <ul id="navibar">%s</ul>''' % items
        return html


    def availableactions(self, d):
        """
        assemble HTML code for the available actions
        
        @param d: parameter dictionary
        @rtype: string
        @return: available actions html
        """
        request = self.request
        _ = request.getText
        html = ''
        available = request.getAvailableActions(d['page'])
        if available:
            available = available.keys()
            available.sort()
            links = []
            for action in available:
                # Always add spaces: AttachFile -> Attach File 
                # XXX TODO do not make a page object just for split_title
                title = Page(request, action).split_title(request, force=1)
                # Use translated version if available
                title = _(title, formatted=False)
                params = '%s?action=%s' % (d['q_page_name'], action)
                link = wikiutil.link_tag(request, params, title)
                links.append(u''.join([ u'<li>', link, u'</li>' ]))
                
            html = u'<ul id="actions">%s</ul>' % u''.join(links)
        return html
    
    def footer(self, d, **keywords):
        """
        Assemble page footer
        
        @param d: parameter dictionary
        @keyword ...:...
        @rtype: string
        @return: page footer html
        """
        dict = {
            'config_page_footer1_html': self.emit_custom_html(self.cfg.page_footer1),
            'config_page_footer2_html': self.emit_custom_html(self.cfg.page_footer2),
            'endpage_html': self.endPage(),
            'edittext_html': self.edittext_link(d, **keywords),
            'footer_fragments_html': self.footer_fragments(d, **keywords),
        }
        dict.update(d)
        
        html = """
%(endpage_html)s

%(config_page_footer1_html)s

<div id="footer">
%(edittext_html)s
%(footer_fragments_html)s
</div>

%(config_page_footer2_html)s
</div>
""" % dict

        return html


def execute(request):
    """
    Generate and return a theme object
        
    @param request: the request object
    @rtype: MoinTheme
    @return: Theme object
    """
    return Theme(request)

