from mod_python import apache,util

import xmlrpclib
from xmlrpclib import ServerProxy

url_mappings={}

def handler(req):
    result=url_mappings[req.subprocess_env['SCRIPT_NAME']](req)
#   except KeyError:
#	req.content_type = "text/html"
#	req.write("blaa:%s" % req.subprocess_env['SCRIPT_NAME'])
#	return apache.OK
    return result


def simplepost(req):
    fsc = util.FieldStorage(req, True)
    
    blogid = fsc.getfirst('blog_id')
    url = fsc.getfirst('url')
    title = fsc.getfirst('title')
    post_body = fsc.getfirst('post_body')
    categories = fsc.getfirst('categories')
    username = fsc.getfirst('username')
    password = fsc.getfirst('password')

    message = None

    if title or post_body:
	req.content_type="text/html"
	proxy = ServerProxy(url)
	cat_list = categories.split(',')
	cat_list = [str(a.strip()) for a in cat_list]

#	proxy.metaWeblog.newPost(int(blogid), username, password,
#				 {'title':title,
#				  'description':post_body,
#				  'categories':cat_list},
#				 True)
	try:
	    proxy.metaWeblog.newPost(1,str(username), str(password), 
				     {'title':str(title),
				      'description':str(post_body),
				      'categories':cat_list},
				     True)
	except xmlrpclib.Fault:
	    message = 'Account Error'
	except xmlrpclib.ProtocolError:
	    message = 'Connection error. Please check your XML-RPC URL is correct'

	if not message:
	    message = "Posted."

	req.write("%s.<br />" % message)
	req.write("<a href='/simplepost/'>Go Back</a>")
    else:
	if not url:
	    url = 'http://myblog.com/xmlrpc.php'
	req.content_type = "text/html"
	req.write("""
<html>
<head><title>Simple Wordpress Post</title></head>
<body>
<p>
Post to your Wordpress blog easily.
</p>
<p>
<form action='/simplepost/' method='POST'>
XML-RPC URL: <input type='text' name='url' value='%s' size='40' /><br />
Blog ID: <input type='text' name='blog_id' value='1' /><br />
Username: <input type='text' name='username' /><br />
Password: <input type='password' name='password' /><br />
Post Title: <input type='text' name='title' size='40' /><br />
Categories (comma-seperated): <input type='text' name='categories' /><br />
Post Body:<br />
<textarea cols=40 rows=8 name='post_body'></textarea><br />
<input type='submit' value='Post' />
</form>
</p>
<p>(C) <a href='http://blog.rsynnott.com/'>Robert Synnott</a></p>
</body>
</html>""" % (url))
    return apache.OK


url_mappings = {"/simplepost/":simplepost
		}


