"""
    MoinMoin - DiffPage action

    Based on the DeletePage action by Jürgen Hermann <jh@web.de>

    A hack of the RenamPage action that is Copyright (c) 2002 Michael Reinsch <mr@uue.org>
    All rights reserved, see COPYING for details.


    This action allows you to diff the actual page with another page

    $Id$
"""

import os
from MoinMoin import wikiutil
from MoinMoin.util.diff import diff
from MoinMoin.Page import Page

class DiffPage:
    """ Diff page action

    Note: the action name is the class name
    """
    def __init__(self, pagename, request):
        self.request = request
        self.pagename = pagename
        self.page = Page(request, pagename)
        self.otherpage = None
        self.error = ''

    def allowed(self):
        """ Check if user is allowed to do this

        This could be a standard method of the base action class, doing
        the filtering by action class name and cfg.actions_excluded.
        """
        may = self.request.user.may
        return (not self.__class__.__name__ in self.request.cfg.actions_excluded and
                may.read(self.pagename))
    
    def render(self):
        """ Render action

        This action return a wiki page with optional message, or
        redirect to other page.
        """
        _ = self.request.getText
        form = self.request.form
        
        if form.has_key('cancel'):
            # User canceled
            return self.page.send_page(self.request)

        # Validate user rights and page state. If we get error here, we
        # return an error message, without the Diff form.
        error = None
        if not self.allowed():
            error = _('You are not allowed to Diff pages in this wiki!')
        elif not self.page.exists():
            error = _('This page does not exist!')
        if error:
            # Send page with an error message
            return self.page.send_page(self.request, msg=error)

        # Try to Diff. If we get an error here, we return the error
        # message with a Diff form.
        elif (form.has_key('Diff') and form.has_key('otherpagename')):
            # User replied to the Diff form with all required items
            self.Diff()
            if not self.error:
#                self.request.http_redirect(self.otherpage.url(self.request))
                return self.request.finish()    

        # A other form request, or form has missing data, or Diff
        # failed. Return a other form with optional error.
        return self.page.send_page(self.request, msg=self.makeform())

    def Diff(self):
        """ Diff pagename and return the other page """
        _ = self.request.getText
        form = self.request.form
        
 
        # Get other name from form and normalize.
        otherpagename = form.get('otherpagename')[0]
        otherpagename = self.request.normalizePagename(otherpagename)

        # Name might be empty after normalization. To save translation
        # work for this extreme case, we just use "EmptyName".
        if not otherpagename:
            otherpagename = "EmptyName"

        # Valid other name
        otherpage = Page(self.request, otherpagename)


        self.request.setContentLanguage(self.request.lang)

        self.request.http_headers()
        wikiutil.send_title(self.request, _('Diff for "%s" and "%s"') % (self.pagename,otherpagename), pagename=self.pagename, allow_doubleclick=0)
        # this should use the formatter, but there is none?
        self.request.write('<div id="content">\n') # start content div
#        self.request.write('<p class="diff-header">')
#        self.request.write('</p>')
        self.request.write(diff(self.request,  self.page.get_raw_body(),otherpage.get_raw_body()))
        self.page.send_page(self.request, count_hit=0, content_only=1, content_id="content-below-diff")
        self.request.write('</div>\n') # end content div
        wikiutil.send_footer(self.request, self.pagename)


                        
    def makeform(self):
        """ Display a Diff page form

        The form might contain an error that happened when trying to Diff.
        """
        from MoinMoin.widget.dialog import Dialog
        _ = self.request.getText

        error = ''
        if self.error:
            error = u'<p class="error">%s</p>\n' % self.error

        d = {
            'error': error,
            'action': self.__class__.__name__,
#            'ticket': wikiutil.createTicket(),
            'pagename': self.pagename,
            'Diff': _('Show Differences'),
            'cancel': _('Cancel'),
            'othername_label': _("Other Page"),
            'comment_label': _("Optional reason for the renaming"),
        }
        form = '''
%(error)s
<form method="post" action="">
<input type="hidden" name="action" value="%(action)s">
<table>
    <tr>
        <td class="label"><label>%(othername_label)s</label></td>
        <td class="content">
            <input type="text" name="otherpagename" value="%(pagename)s">
        </td>
    </tr>
    <tr>
        <td></td>
        <td class="buttons">
            <input type="submit" name="Diff" value="%(Diff)s">
            <input type="submit" name="cancel" value="%(cancel)s">
        </td>
    </tr>
</table>
</form>''' % d
        
        return Dialog(self.request, content=form)        
    
    
def execute(pagename, request):
    """ Glue code for actions """
    DiffPage(pagename, request).render()
    

