#!/usr/bin/env python3
#
# Copyright (C) 2016  Kipp Cannon, Chad Hanna
# Copyright (C) 2019  Patrick Godwin
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


import argparse
import logging
import sys, os
import time
import timeit
import io
import threading 
from gstlal import bottle
import socket
import base64
import uuid
import shutil

from gstlal import far
from gstlal import httpinterface
from gstlal import servicediscovery
from ligo import lw
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from ligo.scald import aggregator
from ligo.scald.io import kafka


def service_domain(gracedb_search, gracedb_pipeline):
	return "%s_%s.%s" % (gracedb_pipeline.lower(), gracedb_search.lower(), servicediscovery.DEFAULT_SERVICE_DOMAIN)

#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#

class ZeroLagCounts(object):
	"""
	A Class to keep track of zero lag counts clustered over 10s fixed windows
	"""

	def __init__(self, fname, verbose = False):
		"""
		fname is the name of the zerolag file read from disk to start the counting
		"""
		self.lock = threading.Lock()
		self.fname = fname
		_, self.zerolag_rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_url(fname, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
		self.counts_dict = {}

	def add_coincs(self, coincs):
		"""
		Iterate over a list of coincs to extract their gps time and
		likelihood ratio value.  GPS times are rounded to the nearest 10s in order to
		cluster events. The max likelihood is tracked in the dictionary over the 10s
		window. Nothing is added to the zerolag histograms. The counts are purely
		internal. Only when a new zerolag histogram is requested will the zerolag
		histogram be updated. That makes it easier to manage late buffers.  No
		additional logic required.  The number of coincs added is returned for 
		logging purposes
		"""
		cnt = 0
		for c in coincs:
			# avoid trigs before LR assigned
			if "likelihood" in c:
				# equiv to 10s clustering
				key = round(c["end"], -1)
				lr = c["likelihood"]
				self.counts_dict[key] = max(self.counts_dict.setdefault(key, lr), lr)
				cnt += 1
		return cnt
		
	def __get_zerolag_rankingstatpdf_xmldoc(self, zlpdf):
		"""
		generate an in memory XML document
		"""
		xmldoc = lw.ligolw.Document()
		xmldoc.appendChild(lw.ligolw.LIGO_LW())
		process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral", paramdict = {})
		far.gen_likelihood_control_doc(xmldoc, None, zlpdf)
		ligolw_process.set_process_end_time(process)
		return xmldoc

	def __add_counts_to_zerolag_pdf(self, zlpdf):
		"""
		Add the internal counts to a zerolag histogram. NOTE!!!! This
		should never be called on the internal zerolag histogram, only on a copy. That
		is why this method is not invoked unless someone is requesting an updated file
		"""
		for lr in self.counts_dict.values():
			zlpdf.zero_lag_lr_lnpdf.count[lr,] += 1

	def web_get_zerolag_rankingstatpdf(self):
		"""
		offer up a new XML doc with the internal counts added to the
		counts that this program was seeded with.  Suitable as a bottle route.
		"""
		with self.lock:
			# always make a copy of the *original* pdf that was
			# loaded at start, never modify it. Just update a copy.
			# Avoids annoying logic for late buffers.  The idea is
			# that you always get the most up to date.
			zlpdf = self.zerolag_rankingstatpdf.copy()
			self.__add_counts_to_zerolag_pdf(zlpdf)
			output = io.BytesIO()
			ligolw_utils.write_fileobj(self.__get_zerolag_rankingstatpdf_xmldoc(zlpdf), output)
			outstr = output.getvalue()
			output.close()
			return outstr

	def snapshot_output_url(self, fname, verbose = False):
		"""
		Write a new XML doc with the internal counts added to disk with fname
		"""
		with self.lock:
			zlpdf = self.zerolag_rankingstatpdf.copy()
			self.__add_counts_to_zerolag_pdf(zlpdf)
			ligolw_utils.write_url(self.__get_zerolag_rankingstatpdf_xmldoc(zlpdf), fname, verbose = verbose, trap_signals = None)


# Read command line options
def parse_command_line():

	parser = argparse.ArgumentParser(description="Online trigger counter")

	# directory to put everything in
	parser.add_argument("--topic", default="triggers", help="Specify the topic where triggers are located.")
	parser.add_argument("--output-period", type = float, default = 3600., help = "Wait this many seconds between writing the output file (default = 3600)")
	parser.add_argument("-u", "--uri", default="kafka://localhost:9092", help="specify Kafka URI to read metrics from. default = kafka://localhost:9092.")
	parser.add_argument("--output", default="zerolag_rankingstatpdf.xml.gz", help = "Choose the output file. Default zerolag_rankingstatpdf.xml.gz")
	parser.add_argument("--gracedb-pipeline", default = "gstlal", help = "Name of pipeline to provide in GracedB uploads (default is gstlal).")
	parser.add_argument("--gracedb-search", default = "LowMass", help = "Name of search to provide in GracedB uploads (default is LowMass).")
	parser.add_argument("-v", "--verbose", default=False, action="store_true", help = "Be verbose.")

	args = parser.parse_args()

	return args


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#

if __name__ == '__main__':

	time_since_last = time.time()
	options = parse_command_line()
	ZLC = ZeroLagCounts(options.output)

	#
	# Stuff to handle bottle route to retrieve xml doc with new counts
	#

	bottle.default_app.push()
	bottle.route('/zerolag_rankingstatpdf.xml')(ZLC.web_get_zerolag_rankingstatpdf)
	httpservers = httpinterface.HTTPServers(
		service_name = "%s.gstlal_ll_inspiral_trigger_counter" % (base64.urlsafe_b64encode(uuid.uuid4().bytes)),
		service_domain = service_domain(options.gracedb_search, options.gracedb_pipeline),
		service_properties = {
			"cwd": os.getcwd(),
			"pid": str(os.getpid()),
		},
		service_discovery = False,#FIXME
		verbose = options.verbose
	)
	open("gstlal_ll_inspiral_trigger_counter_registry.txt", "w").write("http://%s:%s/\n" % (socket.gethostname(), httpservers[0][0].port))


	# set up logging
	log_level = logging.DEBUG if options.verbose else logging.INFO
	logging.basicConfig(format = '%(asctime)s | gstlal_ll_inspiral_trigger_counter : %(levelname)s : %(message)s')
	logging.getLogger().setLevel(log_level)

	# instantiate a consumer to subscribe to all of our topics, i.e., jobs
	client = kafka.Client(options.uri)
	client.subscribe(options.topic)

	# start an infinite loop to keep updating and aggregating data
	logging.info("starting up...")
	while True:

		logging.debug("retrieving data from kafka")
		start = timeit.default_timer()
		msgs = [msg for msg in client.query(max_messages=2000)]
		triggers = aggregator.parse_triggers(msgs)
		elapsed = timeit.default_timer() - start
		logging.debug("time to retrieve data: %.1f s" % elapsed)

		# store and reduce data for each job
		if triggers:
			start = timeit.default_timer()
			logging.debug("adding triggers")
		
			num = ZLC.add_coincs(triggers)

			elapsed = timeit.default_timer() - start
			logging.debug("time to add %d triggers: %.1f s" % (num, elapsed))
		else:
			logging.debug("no triggers to process")

		if (time.time() - time_since_last) > options.output_period:
			shutil.move(options.output, options.output + ".bk")
			ZLC.snapshot_output_url(options.output, verbose = True)
			time_since_last = time.time()

	# close connection to client
	logging.info("shutting down client...")
	client.close()

	#
	# always end on an error so that condor won't think we're done and will
	# restart us
	#

	sys.exit(1)
