import re
import neo_util
import pickle
from os import mkdir

# Set this to where you want the poll state to be stored
polldir = "/var/state/trac/polls"

def title2label(title):
	fix = re.compile('[^a-zA-Z0-9]')
	return fix.sub('', title)

class Poll:
	def __init__(self, title, options):
		self.label = title2label(title)
		self.title = title
		self.options = []
		for option in options:
			self.options.append([option, {}])

	def render(self, hdf):
		html = "<form action='#%s' method='get'>\n" % self.label
		html += "<fieldset>\n<legend>Poll</legend>\n"
		html += "<input type='hidden' name='poll' value='%s'>\n" % self.label

		user = hdf.getValue("trac.authname", "")

		error = ""

		html += "<a name='%s'><strong>%s</strong></a><p/>\n" % (self.label, self.title)

		# Check for existing vote
		if hdf.getValue("args.poll", ""):
			for i, option in enumerate(self.options):
				if hdf.getValue("trac.authname", "") in option[1] and hdf.getValue("args.pollvalue", "") != option[0]:
					error = "<div class='system-message'><strong>Changed your vote.</strong></div>\n"
					del(self.options[i][1][user])
			
		for i, option in enumerate(self.options):
			label = title2label(option[0])
			checked = ""
			if hdf.getValue("args.poll", "") == self.label and hdf.getValue("args.pollvalue", "") == option[0]:
				self.options[i][1][user] = 1
			if hdf.getValue("trac.authname", "") in option[1]:
				checked = "checked"
			voters = ""
			if len(option[1]):
				voters = " (%s)" % ", ".join(option[1].keys())
			html += "<input type='radio' name='pollvalue' value='%s'%s> %s%s<br>\n" % (option[0], checked, option[0], voters)
		html += "<br>\n<input type='submit' value='Vote'>\n"
		html += error
		html += "</fieldset>\n"
		html += "</form>\n"
		return html

def execute(hdf, txt, env):
	args = re.split('\s*;\s*', txt)
	path = "%s/%s" % (polldir, title2label(hdf.getValue("project.name.encoded", "default")))
	try:
		mkdir(path)
	except:
		pass
	path += "/%s.p" % title2label(args[0])
	html = ""
	try:
		poll = pickle.load(open(path, "r"))
	except:
		poll = Poll(args.pop(0), args)
	html += poll.render(hdf)
	pickle.dump(poll, open(path, "w"))
	return html# + "<pre>" + hdf.dump() + "</pre>"

