#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Inkscape extension for storing files in a MoinMoin wiki by xmlrpc put

@copyright: 2009 MoinMoin:ReimarBauer

@license: GNU GPL, see COPYING for details.
"""
import sys
sys.path.append('/usr/share/inkscape/extensions')

# We will use the inkex module with the predefined Effect base class.
import inkex
import xmlrpclib

class MoinXmlrpcPut(inkex.Effect):
    """
    Stores an image to a moinmoin wiki page
    """
    def __init__(self):
        """
        Constructor.
        """
        # Call the base class constructor.
        inkex.Effect.__init__(self)

        # Define string option "--url" with "-u" shortcut and default value
        self.OptionParser.add_option('-u', '--url', action='store',
          type='string', dest='url', default='http://',
          help='What would wiki url you like to access?')

        self.OptionParser.add_option('-n', '--username', action='store',
          type='string', dest='name', default='',
          help='Your name to log in?')

        self.OptionParser.add_option('-p', '--password', action='store',
          type='string', dest='password', default='',
          help='Your password for your name to log in?')

        self.OptionParser.add_option('-w', '--pagename', action='store',
          type='string', dest='wikipage', default='WikiSandBox',
          help='The wikipage you want to access')

        self.OptionParser.add_option('-a', '--attachment', action='store',
          type='string', dest='attachment', default='whiteboard.svg',
          help='The attchment you want to access')


    def effect(self):
        """
        Effect behaviour.
        Overrides base class' method and inserts SVG graphic from moin wiki into SVG document.
        """
        ttmp_orig = self.document.getroot()
        docname = ttmp_orig.get(inkex.addNS('docname',u'sodipodi'))

        data = open('/tmp/'+docname, 'rb').read() # where is that path hidded

        url = self.options.url
        name = self.options.name
        password = self.options.password
        pagename = self.options.wikipage
        attachment = self.options.attachment

        homewiki = xmlrpclib.ServerProxy(url + "?action=xmlrpc2", allow_none=True)
        mc = xmlrpclib.MultiCall(homewiki)
        auth_token = homewiki.getAuthToken(name, password)
        mc.applyAuthToken(auth_token)

        data = xmlrpclib.Binary(data)
        mc.putAttachment(pagename, attachment, data)
        result = mc()
        sys.exit(0)

# Create effect instance and apply it.
effect = MoinXmlrpcPut()
effect.affect()
