#!/usr/bin/env python2.5
#      -*-mode: python -*-    -*- coding: utf-8 -*-

"""

This is a library for doing some simple mediawiki things we need.

It uses pywikipedia, which I don't really know or understand.

So I just took a simply program from there -- editartcile.py (v 0.4)
and hacked it up to be this barebones stuff I needed.

"""

__metaclass__ = type
__version__ = "$Id:"
sig = u" (edited by simple_wiki.py)"

import sys
sys.path.insert(0, '/home/sandro/local/src/pywikipedia')
sys.path.insert(0, '/usr/local/cvs.w3.org/WWW/2008/06/python-cgi/pywikipedia')

import wikipedia
import config

class Poster:

    def __init__(self, family, title, func):
        self.site = wikipedia.getSite(fam=family)
        self.page = wikipedia.Page(self.site, title)
        self.func = func
        self.pageURL = self.site.get_address(title)

    def run(self):
        try:
            old_text = self.page.get(get_redirect = False)
        except wikipedia.NoPage:
            old_text = None

        (new_text, comment) = self.func(old_text)

        if old_text == new_text:
            wikipedia.output(u"Nothing changed")
            return

        self.page.put(new_text, comment=comment, 
                      minorEdit=True, watchArticle=False)
        # might raise wikipedia.EditConflict; okay, pass it on up...

def edit_page(family, title, func):
    """
    Given the (group, title) of a wiki page, retrieve the text from it
    (or None if it doesn't exist), pass that to func, and replace the
    page contents with whatever func returns.

    Hides the mechanics of pywikipedia from everything else.....
    """

    # what family, etc, can do that pageURL?

    try:
        app = Poster(family, title, func)
        app.func = func
        app.run()
    except:
        wikipedia.stopme()
        raise
    wikipedia.stopme()

    return app.pageURL
