"""
Populate voyage data tables from CSV emails.
"""

from datetime import datetime
import email
import logging

from imap import (
	connect_to_server, EmailCheckError, login_to_account, loop_email_messages
)
from message import CSVEmailParser
from settings import (
	EMAIL_FROM, EMAIL_SUBJECT_RE, IMAP_PASSWORD, IMAP_SERVER, IMAP_USERNAME
)


logger = logging.getLogger(__name__)


class VoyageEmailParser(CSVEmailParser):

	required_columns = ('Date/Time', 'LATITUDE', 'LONGITUDE')


	#def process_csv_content(self, content):
		# TODO: Save this content to a CSV file as backup.
		#self.process_csv_rows(StringIO(content))


	def process_csv_row(self, row):
		"""
		Process a single row of CSV from a voyage email.

		Parameters
		----------

		row : dict
			Column names and their values.
		"""

		#print(sorted(row.keys()))

		row_time_str = row['Date/Time']
		row_time = datetime.strptime(row_time_str, '%Y-%m-%d %H:%M')

		latitude = float(row['LATITUDE'])
		longitude = float(row['LONGITUDE'])

		print(latitude)
		raise Exception('Stop here')


def main():
	# Would be nicer if `with IMAP4_SSL() as mail:` was possible.
	mail = connect_to_server(IMAP_SERVER)

	try:
		login_to_account(mail, IMAP_USERNAME, IMAP_PASSWORD)
	except EmailCheckError as e:
		logger.error(e.args[0])
		raise e

	for email_message in loop_email_messages(mail):
		#for header_name, header_value in email_message.items():

		# parsedate_tz() includes the timezone.
		# https://docs.python.org/3.4/library/email.util.html#email.utils.parsedate
		# https://docs.python.org/3.4/library/email.util.html#email.utils.parsedate_tz
		#sent_time = email.utils.parsedate_tz(date)
		#sent_time = email.utils.parsedate(date)


		# parseaddr() splits "From" into name and address.
		# https://docs.python.org/3.4/library/email.util.html#email.utils.parseaddr
		email_from = email.utils.parseaddr(email_message['From'])[1]

		# Skip this message if it did not come from the correct sender.
		if email_from != EMAIL_FROM:
			logger.debug('Email is not from the correct sender (%s).', email_from)
			continue


		subject = email_message['Subject']
		logger.debug('Email subject is "%s".', subject)

		match_data = EMAIL_SUBJECT_RE.match(subject)

		# Skip this message if the subject does not match the format.
		if match_data is None:
			logger.debug('Email subject does not match the required format.')
			continue

		# Get a dict of the values matched in the regex.
		match_dict = match_data.groupdict()

		parser = VoyageEmailParser()

		# Create the table name from the regex values.
		parser.table_name = 'V{season_code}{voyage_code}'.format(**match_dict)

		parser.process_message(email_message)
		break


if '__main__' == __name__:
	logging.basicConfig(level=logging.DEBUG)

	logger.info('Started.')

	main()

	logger.info('Complete.')

@@ -237,16 +237,57 @@
 lParser%0A
+from oracle import connect as db_connect%0A
 from set
@@ -302,16 +302,33 @@
 port (%0A%09
+DATABASE_STRING, 
 EMAIL_FR
@@ -376,17 +376,18 @@
 _SERVER,
- 
+%0A%09
 IMAP_USE
@@ -537,17 +537,16 @@
 TUDE')%0A%0A
-%0A
 %09#def pr
@@ -639,49 +639,185 @@
 %0A%09%09#
-self.process_csv_rows(StringIO(content))%0A
+file_name = ?%0A%09%09#with open(file_name, 'w') as f:%0A%09%09%09#f.write(content)%0A%0A%09%09#self.process_csv_rows(StringIO(content))%0A%09%09#CSVEmailParser.process_csv_content(self, StringIO(content))
 %0A%0A%09d
@@ -1189,16 +1189,49 @@
 UDE'%5D)%0A%0A
+%09%09# TODO: Remove this test code.%0A
 %09%09print(
@@ -1273,16 +1273,88 @@
 ere')%0A%0A%0A
+class VoyageIMAP:%0A%09pass%0A%0A%0A#class VoyageOracle(OracleDatabase):%0A%09#pass%0A%0A%0A
 def main
@@ -1988,17 +1988,16 @@
 (date)%0A%0A
-%0A
 %09%09# pars
@@ -2282,36 +2282,38 @@
 FROM:%0A%09%09%09logger.
-debu
+warnin
 g('Email is not 
@@ -2369,17 +2369,16 @@
 ntinue%0A%0A
-%0A
 %09%09subjec
@@ -2798,16 +2798,71 @@
 rser()%0A%0A
+%09%09#with db_connect(DATABASE_STRING) as db:%0A%09%09if True:%0A%09
 %09%09# Crea
@@ -2902,16 +2902,17 @@
 values.%0A
+%09
 %09%09parser
@@ -2977,16 +2977,57 @@
 _dict)%0A%0A
+%09%09%09#db.create_table(parser.table_name)%0A%0A%09
 %09%09parser
@@ -3058,16 +3058,17 @@
 essage)%0A
+%09
 %09%09break%0A
@@ -3160,16 +3160,31 @@
 'Started
+ reading emails
 .')%0A%0A%09ma
@@ -3207,16 +3207,31 @@
 fo('
-Complete
+Finished reading emails
 .')%0A

Add comments and test code to main module