#!/usr/bin/python3
# Script to decode protobuf, or something

# Example code from https://gtfs.org/documentation/realtime/language-bindings/python/ which probably won't work
from google.transit import gtfs_realtime_pb2
import requests
from pprint import pprint
import pymysql
import logging
import localconfig as config
import argparse


def main(all_trip_updates):
	logging.info("Fetching GTFS feed")
	feed = gtfs_realtime_pb2.FeedMessage()
	# We're only dumping the Trip Updates portion of the feed currently, but it's basically identical milliseconds to run against either feed, so already using the full one
	response = requests.get('https://gtfs.edmonton.ca/TMGTFSRealTimeWebService/GTFS-RealTime/TrapezeRealTimeFeed.pb')
	feed.ParseFromString(response.content)
	
	oldest_timestamp = None
	
	try:
		with localcon.cursor() as cursor:
			
			# If we were time-gating,
			# sql = "DELETE FROM trip_stop_updates where`timestamp` < %s"
			# cursor.execute(sql, (oldest_timestamp))
			
			logging.info("Put the deletion in the queue")
			sql = "DELETE FROM trip_stop_updates;"
			cursor.execute(sql)
			
			for entity in feed.entity:
				logging.debug("Processing GTFS entities")
				if entity.HasField('trip_update'):
					e = entity.trip_update
					if e.trip.trip_id:
						#print("Would do something")
						#pprint(dir(e))
						for stfu in e.stop_time_update:
							humandebug = f"route_id: {e.trip.route_id} | trip_id: {e.trip.trip_id} | direction_id: {e.trip.direction_id} | start_time: {e.trip.start_time} | startdate: {e.trip.start_date}, stop_id: {stfu.stop_id}, delay: {stfu.departure.delay}, time: {stfu.departure.time}, timestamp: {e.timestamp}"
						
							if stfu.departure.delay == 0 and all_trip_updates == False:
								# This better be combined with cleaning up old entries in some form!
								logging.debug(f"Skipping departure delay 0: {humandebug}")
								continue
							
							# print(stfu)
							
							
							
							logging.debug(humandebug)
							
							if stfu.departure.time <= 0:
								logging.warning(f"Departure time seems wack! Skipping this: {humandebug}")
								continue
							
							# If we're more targeted because we opened it up in some other way like not just deleting the whole table, we might want this:
							# if oldest_timestamp is None:
							# 	oldest_timestamp = e.timestamp
							# if e.timestamp < oldest_timestamp:
							# 	logging.info(f"New oldest timestamp, {oldest_timestamp}")
							# 	oldest_timestamp = e.timestamp
							
							# Create a new record
							sql = "REPLACE INTO trip_stop_updates (`trip_id`,`stop_id`, `route_id`,`direction_id`,`delay`,`time`, `timestamp`) VALUES (%s, %s, %s, %s, %s, %s, %s)"
							cursor.execute(sql, (e.trip.trip_id, stfu.stop_id, e.trip.route_id, e.trip.direction_id, stfu.departure.delay, stfu.departure.time, e.timestamp))
			
			# If we're more targeted because we opened it up in some other way like not just deleting the whole table, we might want this:
			#sql = "DELETE FROM trip_stop_updates where`timestamp` < %s"
			#cursor.execute(sql, (oldest_timestamp))
			
		localcon.commit()
	finally:
		logging.info("Committed fresh realtime data")

if __name__ == '__main__':
	logger = logging.getLogger(__name__)
	
	# Define the arguments allowed and how to use them (both to the user and to this script)
	parser = argparse.ArgumentParser(description='Currently just graps the ETS "trapeze" feed and stuffs it into a MariaDB database table')
	parser.add_argument("-a", "--all-trip-updates", help="Return all trip_updates even if their 'delay' is 0", action="store_true")
	parser.add_argument("-v", "--verbose", help="Be verbose", action="store_true")
	parser.add_argument("--debug", help="Be probably unhelpfully verbose", action="store_true")
	# TODO: add "--cleanup-strategy" rather than hardcoding
	
	args = parser.parse_args()
	
	# TODO: really abuse https://docs.python.org/3/library/logging.html#logrecord-attributes
	if args.debug:
		logging.basicConfig(level=logging.DEBUG, format="%(relativeCreated)d %(levelname)s: %(message)s")
	elif args.verbose:
		logging.basicConfig(level=logging.INFO, format="%(relativeCreated)d %(levelname)s: %(message)s")
	else:
		logging.basicConfig(level=logging.ERROR, format="%(asctime)s %(levelname)s: %(message)s")
	
	
	logging.info("Open the connection to our database server")
	localcon = pymysql.connect(host=config.dbhost,
		user=config.dbuser,
		password=config.dbpass,
		db=config.dbname,
		charset=config.dbchar,
		cursorclass=pymysql.cursors.DictCursor
	)
	
	main(args.all_trip_updates)
	localcon.close()
