#!/usr/bin/python
# Metlstorm, 2k7. <metlstorm@storm.net.nz>
# Hacky script to find out what seat I was on. 
# Will obviously bitrot as AirNZ frob with their site.
"""
Metl Roto-Airpoint-Seaterator V0.1
Logging in... Air New Zealand - My Account
Finding where you sat on NZ458 out of WLG on 25/05/2007
Trying... 1A 1B 1C 1D 1E 1F 2A 2B 2C 2D 2E 2F 3A 3B 3C 3D 3E 3F 4A 4B 4C 4D 4E 4F 5A 5B 5C 5D 5E 5F 6A 6B 6C 6D 6E 6F 7A 7B 7C 7D 7E 7F 8A 8B 8C 8D 8E 8F 9A 9B 9C 9D 9E 9F 10A 10B 10C 10D 10E 10F 10F
Woot!: 10F
"""

from mechanize import Browser
import ClientForm
import time
import sys

#------[ Edit me ]----

AIRPOINTS=""	# <--- Airpoints number
PASS=""			# <--- Password

DAY="25"		# Day of month
MON="05/2007"	# Matches the format of their <option value=...
CITY="WLG"		# Origin Airport code
FLIGHT="NZ458"	# Flight number
ROW=range(1,28) # Seat rows to search
SEAT="ABCDEF"	# You do remember how wide the plane was right?

LOGINFORM="https://registration.airnewzealand.com/spr/login/login.jsp"
MISSINGFORM="https://registration.airnewzealand.com/spr/my_account/missingairpoints.jsp"

print "Metl Roto-Airpoint-Seaterator V0.1"

if AIRPOINTS == "":
	print "Edit me to set up your details!"
	sys.exit(1)

br = Browser()
print "Logging in...",
r = br.open(LOGINFORM)
print br.title()
br.select_form(name="form1")
br["username"] = AIRPOINTS
br["password"] = PASS

r = br.submit()
data = r.read()
# Contains javascript redirect to memberservices.jsp, which has menus etc.
if data.find("memberservices.jsp") == -1:
	print "Oh noes!"
	print data
	sys.exit(1)

done = False
print "Finding where you sat on %s out of %s on %s/%s" % (FLIGHT, CITY, DAY, MON) 
print "Trying...",
for row in ROW:
	for seat in SEAT:
		br.open(MISSINGFORM)
		print "%d%s" % (row, seat),
		sys.stdout.flush()

		br.select_form(name="details")
		br["day0"]=[DAY]
		br["monthYear0"]=[MON]
		br["city0"] = [CITY]
		ClientForm.Item(br.form.find_control("flight0"), dict(contents=FLIGHT,value=FLIGHT))
		br["flight0"] = [FLIGHT]
		br["seatRow0"] = ["%02d" %row]
		br["seatLetter0"]= [seat]
		br.form.find_control("pageAction").readonly = False
		br["pageAction"] = "process"

		rSub = br.submit()
		page = rSub.read()
		fn = "log-%s-%s-%s-%s-%s%s.html" % (DAY, MON, CITY, FLIGHT, row, seat)
		fn = fn.replace("/", "-")
		fo = open(fn, "w")
		fo.write(page)
		fo.close()

		if page.find("ERROR ROW") == -1:
			print "%s%s\nWoot!: %s%s" % (row,seat,row, seat)
			sys.stdout.flush()
			done = True
			break
		time.sleep(1)
	if done:
		break


