#!/usr/bin/python
import urllib.parse, urllib.request, urllib.error
import re

import config
from emailgateway import EmailGateway
from time import sleep

nosectex = b"NO SECTIONS FOUND FOR THIS INQUIRY."

postdata = {
	'CAMPUS' : config.campus,
	'TERMYEAR': config.termyear,
	'CORE_CODE' : "AR%",
	'SUBJ_CODE' : "%",
	'SCHDTYPE' : "%",

	'BTN_PRESSED' : "FIND class sections",
	'inst_name' : "",
}

gateway = EmailGateway(config.from_addr, config.smtp_host, config.smtp_port, config.smtp_tls, config.smtp_user, config.smtp_pass)

def check_sections():
	for crn in config.crns:
		postdata['crn'] = crn
		postdata['open_only'] = ""

		# ensure that section exists
		#encoded = urllib.parse.urlencode(postdata)
		#page = urllib.request.urlopen(url, data=encoded)
		#result = page.read()
		
		#if re.search(nosectex, result) is not None:
			#print("CRN %d: Section does not exist" % crn)

		# check to see if there are open seats
		postdata['open_only'] = "on"
		encoded = urllib.parse.urlencode(postdata)
		page = urllib.request.urlopen(config.url, data=encoded)
		result = page.read()

		if re.search(nosectex, result) is None:
			#print("CRN %d: Section open" % crn)
			gateway.send(config.notify_addr, "CRN %d Open" % crn, "The section with CRN %d is now open" % crn)
		#else:
		#	print("CRN %d: Section full" % crn)

check_sections()


@@ -197,16 +197,194 @@
 NQUIRY.%22
+%0Acoursenrex = b%22%3CTD class=deleft style=background-color:WHITE%3E%5Cn%3CFONT SIZE=%5C%221%5C%22%3E(.+?)%3C%5C/FONT%3E%5Cn%3C%5C/TD%3E%22%0Acoursetitex = b%22%3CTD class=deleft style=background-color:WHITE%3E(.+?)%3C%5C/TD%3E%22
 %0A%0Apostda
@@ -1100,16 +1100,17 @@
 seats%0A%09%09
+#
 postdata
@@ -1306,146 +1306,532 @@
 %0A%09%09%09
-#print(%22CRN %25d: Section open%22 %25 crn)%0A%09%09%09gateway.send(config.notify_addr, %22CRN %25d Open%22 %25 crn, %22The section with CRN %25d is now open%22 %25
+coursenr = re.search(coursenrex, result).group(1).decode('ascii')%0A%09%09%09coursetitle = re.search(coursetitex, result).group(1).decode('ascii')%0A%0A%09%09%09#print(%22CRN %25d: Section open%22 %25 crn)%0A%09%09%09gateway.send(config.notify_addr, %22coursenotify: %25s open%22 %25 coursenr, %22%22%22Hello,%0A%0AThis message is to inform you that at last run, coursenotify%0Afound an open seat in %25s %25s, CRN %25d.%0A%0AYou will continue to receive notifications the next time coursenotify%0Aruns unless you remove this CRN from your configuration.%0A%22%22%22 %25 (coursenr, coursetitle,
  crn)
+)
 %0A%09%09#

Change emails to be a little more user-friendly and specify the course number and name as well