#! /usr/bin/python
import xmlrpclib
import getpass
import sys
import os
import time
import md5
import string
import xml.dom
import xml.dom.minidom
from xml.dom.minidom import parse, parseString

def MakePost(file):
	# Load file, and post to LJ
	dom = parse(file)
	# Get the root node
	topnode = dom.documentElement
	# Make sure that we can understand it
	if string.lower(topnode.tagName) != "post": 
		raise "\"" + file + "\" is not a post file."
	post = {'username':username, 'auth_method': 'challenge', 'auth_challenge': '', 'auth_response': '', 'event':'', 'subject':'', 'security':'public','year':'', 'mon':'', 'day':'','hour':'', 'min':'','props':{'current_music':'', 'current_mood':''}}
	for cnode in topnode.childNodes:
		if not cnode.nodeName:
			print cnode.nodeValue
			pass
		elif string.lower(cnode.nodeName) == "subject":
			# Get the subject
			post['subject'] = cnode.firstChild.nodeValue
			print "Grabbed subject: " + post['subject']
		elif string.lower(cnode.nodeName) == "mood":
			post['props']['current_mood'] = cnode.firstChild.nodeValue
			print "Grabbed mood: " + post['props']['current_mood']
		elif string.lower(cnode.nodeName) == "event":
			post['event'] = getInnerXML(cnode)
			print "Grabbed event: " + post['event']
		elif string.lower(cnode.nodeName) == "security":
			post['security'] = cnode.firstChild.nodeValue
			print "Grabbed security: " + post['security']
		elif string.lower(cnode.nodeName) == "music":
			post['props']['current_music'] = cnode.firstChild.nodeValue
			print "Grabbed music: " + post['props']['current_music']
		elif string.lower(cnode.nodeName) == "time":
			timestring = cnode.firstChild.nodeValue
			#yyyymmdd-HH:MM
			post['year'] = timestring[0:4]
			post['mon'] = timestring[4:6]
			post['day'] = timestring[6:8]
			post['hour'] = timestring[9:11]
			post['min'] = timestring[12:14]
	#sys.exit(0)

	# Here's where we start doing stuff
	ljserver = xmlrpclib.Server("http://livejournal.com/interface/xmlrpc")
	# Get our challenge from the LJ server
	challenge = ljserver.LJ.XMLRPC.getchallenge()
	# Create our response
	post['auth_challenge'] = challenge['challenge']
	post['auth_response'] = md5.new(challenge['challenge'] + md5.new(password).hexdigest()).hexdigest()
	try:
		result = ljserver.LJ.XMLRPC.postevent(post)
	except Exception, v: 
		print "ERROR", v

	# And now it should be done
	
			
	dom.unlink()

def getInnerXML(node):
	innerxmlstring = ""
	for cnode in node.childNodes:
		if cnode.nodeType == cnode.ELEMENT_NODE:
			innerxmlstring += "<" + cnode.tagName + ">" + getInnerXML(cnode) + "</" + cnode.tagName + ">"
		elif cnode.nodeType == cnode.TEXT_NODE:
			innerxmlstring += cnode.nodeValue
	return innerxmlstring


if __name__=="__main__":
	if len(sys.argv) > 1: # Somebody has passed an argument
		# Handle arguments here.
		for arg in sys.argv[1:]:
			if arg== "-h" or arg == "--help":
				# Do help stuff here
				pass
				
	# Get user login info
	print "First we need to get your LJ login information."
	print "For security reasons, these values cannot be passed as parameters."
	username = raw_input("LJ Username: ")
	password = getpass.getpass("LJ password: ")
	
	# Begin endless loop. We check every minute if we should post something.
	while(True):
		flist = os.listdir(".")
		for file in flist:
			try:
				# Check if time matches
				if file[:14] == time.strftime("%Y%m%d-%H:%M"):
					# Got a hit
					MakePost(file)
			except:
				pass
				
			
		# now wait for the next minute
		time.sleep(60)
	
