#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 
import os
import sys

#cgitb.enable()

treecounts = (
        (16, 16, 15),      # druid
        (16, 14, 16),      # hunter
        (16, 16, 17),      # mage
        (15, 15, 15),      # paladin
        (15, 16, 16),      # priest
        (15, 19, 17),      # rogue
        (15, 16, 15),      # shaman
        (17, 17, 16),      # warlock
        (18, 17, 17)       # warrior
);

classname = ("druid","hunter","mage","paladin","priest","rogue","shaman","warlock","warrior")
classid = (11,3,8,2,5,4,7,9,1)
classindex = 0

def encode_wowhead(talentstr, classindex):
	#print 'Encoding wowhead'
	#print 'talentstr is', talentstr
	#print 'classindex is', classindex

	encrypt_string = '0zMcmVokRsaqbdrfwihuGINALpTjnyxtgevElBCDFHJKOPQSUWXYZ123456789Z'
	# begin output with the class
	outstr = encrypt_string[classindex*3]

	tc = treecounts[classindex]
	build_trees = talentstr[0:tc[0]], \
		talentstr[tc[0]:tc[0]+tc[1]], \
		talentstr[tc[0]+tc[1]:tc[0]+tc[1]+tc[2]]

	for curtree in build_trees:
		encode = ''
		b = curtree.rstrip('0')
		for i in range(0, len(b), 2):
			tens = int(b[i])
			ones = 0
			if i+1 < len(b):
				ones = int(b[i+1])
			#print 'tens is',tens,'ones is',ones
			encode += encrypt_string[tens*6+ones]
		#print encode
		if len(b) == len(curtree):
			outstr += encode
		else:
			outstr += encode + encrypt_string[62]
	# strip remaining Zs
	outstr = outstr.rstrip(encrypt_string[62])
	return outstr

def decode_wowhead(whstr):
	global classindex
	encrypt_string = '0zMcmVokRsaqbdrfwihuGINALpTjnyxtgevElBCDFHJKOPQSUWXYZ123456789Z'

	classindex = int(encrypt_string.find(whstr[0]) / 3)

	# fix for rogues?
	if classindex == 9: classindex = 5

	outstr = ""
	curtree = 0
	curstr = ""

	for c in whstr[1:]:
		if c == 'Z':
			curstr += "".zfill(treecounts[classindex][curtree] - len(curstr))
			outstr += curstr
			curstr = ""
			curtree += 1
		else:
			in_val = int(encrypt_string.find(c))
			curstr += str(int(in_val / 6))
			if len(curstr) >= treecounts[classindex][curtree]:
				outstr += curstr
				curstr = ""
				curtree += 1
				if curtree >= 3:
					break;
			else:
				curstr += str(in_val % 6)

		if len(curstr) >= treecounts[classindex][curtree]:
			outstr += curstr
			curstr = ""
			curtree += 1

	if curstr != "":
		curstr += "".zfill(treecounts[classindex][curtree] - len(curstr))
		outstr += curstr

	return outstr

def parse_and_redirect(url):
	global classindex
	if 'wowhead' in url.lower():
		blobindex = url.lower().find('talent=') + 7
		if blobindex == 6: #find returned -1
			blobindex = url.lower().find('talent/?') + 8
		outstr = decode_wowhead(url[blobindex:])
	elif 'worldofwarcraft.com/info/classes' in url.lower():
		for i in range(0, len(classname)):
			if classname[i] in url:
				classindex = i
		blobindex = url.lower().find('talents.html') + 13
		outstr = url[blobindex:]
	elif 'www.wow-europe.com/en/info/basics/talents' in url.lower():
		for i in range(0, len(classname)):
			if classname[i] in url:
				classindex = i
		blobindex = url.lower().find('talents.html') + 13
		outstr = url[blobindex:]
	else:
		print "Unrecognized URL"
		sys.exit(0)

	# Redirect for wowprovider currently not working -dk 2015-07-28
#	for i in range(25,1,-1):
#		outstr = outstr.replace("".zfill(i),chr(ord('a')+i),1)
#	print "Location:http://www.wowprovider.com/?talent=11215875_" + str(classid[classindex]) + "_8" +outstr + "\r\n\r\n"
#	print "Location:http://www.google.ca/\r\n\r\n"

    # wowprovider is down so encode wowhead style
	outstr = encode_wowhead(outstr, classindex)
	print "Location:http://db.vanillagaming.org/?talent#"+outstr+"\r\n\r\n"

	sys.exit(0)

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
url = form.getvalue('old_url')
if url:
	parse_and_redirect(url)

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>VANILLA WoW TALENTS</title>'
print '</head>'
print '<body>'
print '<h1>mewse\'s vanilla talent decoder</h1>'
print '<p>Enter an old wowhead or blizzard talent calculator URL and this'
print 'script will redirect you to the appropriate build on the'
print 'wowprovider 1.12.1 calculator.</p>'
print '<p>Examples:</p>'
print '<ul><li>Hunter 5/34/12: http://www.worldofwarcraft.com/info/classes/hunter/talents.html?5000000000000000505510305130513300042000000000</li>'
print '<li>Warrior 31/5/15: http://www.wowhead.com/?talent=TqGxdhboxzVZxV00x</li></ul>'
print '<form action="' + os.environ["SCRIPT_NAME"] + '" method="post">'
print 'Paste the old URL here: <input type="text" size="80" name="old_url">'
print '<input type="submit" value="Submit" />'
print '</form>'
#for i in os.environ.keys():
#	print "<b>%20s</b>: %s<br>" % (i, os.environ[i])
print '</body>'
print '</html>'
