# Script to create a slightly more useful attempt
# at a prospecting guide.

import sys
print "Don't run this script - use make-prospectingguide-new.py instead"
sys.exit(0)

areas = ['', '1a','1b','1c','1d', '2a', '2b', '2c', '2d', '3', '4', '5', '6','7', '8a', '8b', '8c', '8d', '9', '10', '11']

areanames = {
	'':	'Location unclear',
	'1a':	'1a – Plateau: around Top Camp',
	'1b':	'1b – Western plateau near 182',
	'1c':	'1c – Eastern plateau near 204 walk-in path',
	'1d':	'1d – Further plateau around 76',
	'2a':	'2a – Southern Schwarzmooskogel near 201 path and the Nipple',
	'2b':	'2b – Eishöhle area',
	'2c':	'2c – Kaninchenhöhle area',
	'2d':	'2d – Steinbrückenhöhle area',
	'3':	'3 – Bräuning Alm',
	'4':	'4 – Kratzer valley',
	'5':	'5 – Schwarzmoos-Wildensee',
	'6':	'6 – Far plateau',
	'7':	'7 – Egglgrube',
	'8a':	'8a – Loser south face',
	'8b':	'8b – Loser below Dimmelwand',
	'8c':	'8c – Augst See',
	'8d':	'8d – Loser-Hochganger ridge',
	'9':	'9 – Gschwandt Alm',
	'10':	'10 – Altaussee',
	'11':	'11 – Augstbach'
	}

areacolours = {
	'1a' : '#00ffff',
	'1b' : '#ff00ff',
	'1c' : '#ffff00',
	'1d' : '#ffffff',
	'2a' : '#ff0000',
	'2b' : '#00ff00',
	'2c' : '#008800',
	'2d' : '#ff9900',
	'3'  : '#880000',
	'4'  : '#0000ff',
	'6'  : '#000000', # doubles for surface fixed pts
	'7'  : '#808080'
	}


cavelists={}
for a in areas: cavelists[a]=[]


def chomp(s):
	if not s: return s
	if s[-1]=="\n": return chomp(s[:-1])
	elif s[-1]==" ": return chomp(s[:-1])
	else: return s

def find_effective_number(c):
	"""Determine an appropriate number to use."""
	if c["Kataster Number"]:
		return c["Kataster Number"]
	else:
		return c["Unofficial number"]

def longnumber(c, number):
	"""Both numbers"""
	if (c["Unofficial number"] and c["Unofficial number"] != number):
		return number + " (" + c["Unofficial number"] + ")"
	else:
		return number

def find_location(cave):
	for fixtype in ["tag point in dataset", "other point in dataset", "exact entrance in dataset (drip line/highest enclosed contour)", "GPS post SA", "GPS pre SA"]:
		if(cave[fixtype]):
			return positions[cave[fixtype]]
	return 0
			

def munge_allposline(line):
	x, y, z, name = re.match(r'\(([0-9.]*?),\s*([0-9.]*?),\s*([0-9.]*?)\s*\)\s*(.*)\n', line).groups()
	x,y, z = map(float, [x,y,z])
	return (name, x,y,z)

def is_explored(cave):
	s = cave["Kat Status Code"]
	if(not s): return "<td></td>"
	s = s.replace("(?)","")
	if s[-1] == " ": s=s[:-1]
	if (not s): print "Rogue space in " + find_effective_number(cave)
	return "<td>"+s[-1]+"</td>"

def is_tagged(cave):
	s = chomp(cave["Marking"].replace("(?)", ""))
	if not s and cave["Multiple entrances"] in ["yes", "entrance", "last entrance"]:
		return "<td></td>"
	if s == "Tag": return "<td class=\"good\">%s</td>" % s
	if s in ["Retag", "Paint", "Spit"]: return "<td class=\"bad\">%s</td>" % s
	if s == "Unmarked" or not s: return "<td class=\"awful\">None</td>"
	print "Unrecognised marking status on %s: %s" % (find_effective_number(cave), repr(s))
	return "<td>ERROR</td>"

def findability_color(cave):
	if cave["Findability"] == "Surveyed": return "good"
	elif cave["Findability"] == "Refindable": return "bad"
	elif cave["Findability"] == "Lost": return "awful"
	else:	return ""

def is_underground_surveyed(cave):
	s = chomp(cave["Underground drawn survey"])
	if(cave["Multiple entrances"] not in ["", "yes"]): return "<td></td>"
	if not s:
		return "<td class=\"awful\">None</td>"
	if s and (s.find("<img") > -1 or s.find("<a") > -1):
		return "<td class=\"good\">Yes</td>"
	else:
		return "<td class=\"bad\">Missing</td>"

def has_photo(cave):
	s = chomp(cave["Photo of location"])
	if ((cave["Multiple entrances"] not in ["", "yes"]) and chomp(cave["Autogen file"]) == ""):
		return "<td></td>"
	if not s:
		return "<td class=\"awful\">None</td>"
	if s and (s.find("<img") > -1 or s.find("<a") > -1):
		return "<td class=\"good\">Yes</td>"
	else:
		return "<td class=\"bad\">Missing</td>"


import csv, re, time
cavetabfile = file("../CAVETAB2.CSV")
fieldnames=chomp(cavetabfile.next()).replace('"','').split(",")
cavetab = csv.DictReader(cavetabfile, fieldnames)

positionfile = file("../all.pos")
positionfile.next()
positions = {}
print "Munging all.pos"
for stn in positionfile:
	t = munge_allposline(stn)
	positions[t[0]] = (t[1],t[2],t[3])
print "Done"

htmlfile = file("../../handbook/prospecting_guide_short.html", "w")

htmlfile.write("<html><head><title>Prospecting Guide</title>\n")
htmlfile.write("""
<style type="text/css">
.locn { font-size: x-small }
.bad	{ background-color: #ff9955; text-align: center }
.good	{ background-color: #99ff99; text-align: center }
.awful	{ background-color: #ff5555; text-align: center }
</style></head>""")
htmlfile.write("<body><h1>Prospecting Guide: Summary</h1>")
htmlfile.write("<p>Generated " + time.strftime("%x %X") + "</p>\n")
htmlfile.write("<p><b>Notes:</b></p><ul><li>A marking status of \"Retag\" means a tag is in place but it carries a provisional number, or in some cases an incorrect number, and needs replacing with a new tag.</li>\n<li>Kataster status codes indicate the size of a cave, its character and its exploration status, as described <a href=\"../katast.htm\">here</a>.</li><li>For more info on each cave, see the links to detailed description pages.</li></ul><table border=\"1\">\n")

cachednumber = ""
cachedarea = ""
cachedname = ""

for cave in cavetab:
	if cave["Link file"]: continue
	number = find_effective_number(cave)
	if(cave["Multiple entrances"] not in ["", "yes"]):
		number = "&mdash;" + cachednumber + cave["Entrances"]
		shortnumber = cachednumber
		if not cave["Area"]: cave["Area"] = cachedarea
		#if not cave["Name"]: cave["Name"] = cachedname
	else: 
		cachednumber = number
		shortnumber = number
		cachedname = cave["Name"] or cave["Unofficial Name"]
		cachedarea = cave["Area"]
		
	area = cave["Area"]
   	# We have some areas like '2b or 4 (unclear)' - just chop the space
	# and everything after it for these.
	area = re.sub(r' .*', "", area)
	if area == '1626' or area == 'nonexistent': continue

	loctuple = find_location(cave)
	if(cave["Multiple entrances"] == "yes"):
		locn = "<td colspan=\"3\">&nbsp;</td>"
	elif(loctuple):
		locn = "<td class=\"locn good\">%d</td><td class=\"locn good\">%d</td><td class=\"locn good\">%d</td>" % loctuple 
	else:
		locn = "<td colspan=\"3\" class=%s>" % findability_color(cave) + (cave["Findability"] or '?') + "</td>"
	try:
		cavelists[area].append((number, cave, locn))
	except:
		print "Bad area '%s' for cave %s" % (area, number)

for area in areas:
	if area:
		htmlfile.write("<tr><td colspan=\"9\" style=\"padding-top: 3em; padding-bottom: 1em; border: 0; text-align: center\"><h3>%s</h3></td></tr>" % areanames[area])
	else:
		htmlfile.write("<tr><td colspan=\"9\" style=\"padding-top: 3em; padding-bottom: 1em; text-align: center\"><h3>Location unclear</h3></td></tr>")
	htmlfile.write("<tr><th>Cave Number</th><th>Name</th><th>Finished</th><th>Surveyed</th><th>Marked</th><th>Photoed</th><th>E</th><th>N</th><th>Alt</th><th>Location</th>")

	for (number, cave, locn) in cavelists[area]:
		if cave["Autogen file"]:
			htmlfile.write("<tr><td><a href=\"../%s\">%s</a></td><td><a id=\"id%s\">%s</a></td>" % (cave["Autogen file"], longnumber(cave, number), number.replace("&mdash;", ""), cave["Name"] or cave["Unofficial Name"]))
		else:
			htmlfile.write("<tr><td>%s</td><td><a id=\"id%s\">%s</a></td>" % (longnumber(cave, number), number.replace("&mdash;", ""), cave["Name"] or cave["Unofficial Name"]))	

		htmlfile.write(is_explored(cave))
		htmlfile.write(is_underground_surveyed(cave))
		htmlfile.write(is_tagged(cave))
		htmlfile.write(has_photo(cave))

		htmlfile.write(locn)
		if(cave["Findability"] != "Surveyed" and cave["Multiple entrances"] != "yes"):
			htmlfile.write("<td class=\"locn\">%s %s</td>" % (cave["Location"], cave["Bearings"]))
		htmlfile.write("</tr>\n")
	
htmlfile.write("</table>\n")


htmlfile.write("</body></html>")
htmlfile.close()