#!/usr/bin/python3

from datetime import datetime
from datastore import Datastore

def detect_schema (conn):
	with conn.cursor() as cursor:
		qry = "SELECT meta->>'_schema' AS schema, tstamp, age(current_timestamp, tstamp) age FROM real_time_inputs WHERE meta ? '_schema' AND age(current_timestamp, tstamp) < '02:00:00' ORDER BY tstamp DESC LIMIT 1"
		cursor.execute(qry)
		res = cursor.fetchone()
		if res and len(res):
			return res[0]
	return None

if __name__ == '__main__':
	import argparse

	ap = argparse.ArgumentParser()
	ap.add_argument("-s", "--schema", required=False, default=None, help="survey where to insert the event")
	ap.add_argument("-t", "--tstamp", required=False, default=None, help="event timestamp")
	ap.add_argument("-l", "--label", required=False, default=None, action="append", help="event label")
	ap.add_argument('remarks', type=str, nargs="+", help="event message")
	args = vars(ap.parse_args())


	db = Datastore()
	db.connect()

	if args["schema"]:
		schema = args["schema"]
	else:
		schema = detect_schema(db.conn)

	if args["tstamp"]:
		tstamp = args["tstamp"]
	else:
		tstamp = datetime.utcnow().isoformat()

	message = " ".join(args["remarks"])

	print("new event:", schema, tstamp, message, args["label"])

	if schema and tstamp and message:
		db.set_survey(schema)
		with db.conn.cursor() as cursor:
			qry = "INSERT INTO event_log (tstamp, remarks, labels) VALUES (%s, replace_placeholders(%s, %s, NULL, NULL), %s);"
			cursor.execute(qry, (tstamp, message, tstamp, args["label"]))
			db.maybe_commit()
