#!/usr/bin/env python3
#
# Copyright (C) 2013--2015  Kipp Cannon
#
# 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.


### A program to listen to lvalerts, download the psd from gstlal gracedb events, plot it, and upload the results


#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


import logging
from optparse import OptionParser
import os.path
import sys
import urllib.parse as urlparse
import json


import lal


from glue.ligolw import utils as ligolw_utils
from gstlal import lvalert_helper
from gstlal.plots import psd as plotpsd
from ligo.gracedb import rest as gracedb


import matplotlib
matplotlib.rcParams.update({
	"font.size": 10.0,
	"axes.titlesize": 10.0,
	"axes.labelsize": 10.0,
	"xtick.labelsize": 8.0,
	"ytick.labelsize": 8.0,
	"legend.fontsize": 8.0,
	"figure.dpi": 100,
	"savefig.dpi": 100,
	"text.usetex": True,
	"path.simplify": True
})


#
# =============================================================================
#
#                                   Library
#
# =============================================================================
#


def get_psds(gracedb_client, graceid, filename = "psd.xml.gz", ignore_404 = False):
	response = lvalert_helper.get_filename(gracedb_client, graceid, filename = filename, ignore_404 = ignore_404)
	if response is None:
		return None
	return lal.series.read_psd_xmldoc(ligolw_utils.load_fileobj(response, contenthandler = lal.series.PSDContentHandler)[0])


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


def parse_command_line():
	parser = OptionParser()
	parser.add_option("--format", default = "png", help = "Set file format by selecting the extention (default = \"png\").")
	parser.add_option("--no-upload", action = "store_true", help = "Write plots to disk.")
	parser.add_option("--skip-404", action = "store_true", help = "Skip events that give 404 (file not found) errors (default is to abort).")
	parser.add_option("--gracedb-service-url", default="%s" % gracedb.DEFAULT_SERVICE_URL, help = "GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, graceids = parser.parse_args()

	if not graceids:
		# FIXME:  lvalert_listen doesn't allow command-line
		# options, enable logging for online analysis
		options.verbose = True

	# can only call basicConfig once (otherwise need to switch to more
	# complex logging configuration)
	if options.verbose:
		logging.basicConfig(format = "%(asctime)s:%(message)s", level = logging.INFO)
	else:
		logging.basicConfig(format = "%(asctime)s:%(message)s")

	return options, graceids


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


options, graceids = parse_command_line()


if not graceids:
	lvalert_data = json.loads(sys.stdin.read())
	logging.info("%(alert_type)s-type alert for event %(uid)s" % lvalert_data)
	logging.info("lvalert data: %s" % repr(lvalert_data))
	if "filename" in lvalert_data["data"]:
		filename = os.path.split(urlparse.urlparse(lvalert_data["data"]["filename"]).path)[-1]
		if filename not in (u"psd.xml.gz",):
			logging.info("filename is not 'psd.xml.gz'.  skipping")
			sys.exit()
		graceids = [str(lvalert_data["uid"])]
	else:
		logging.info("json key filename not in lvalert data, skipping")


gracedb_client = gracedb.GraceDb(service_url = options.gracedb_service_url)


for graceid in graceids:
	psds = get_psds(gracedb_client, graceid, ignore_404 = options.skip_404)
	if psds is None:
		continue

	coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)

	#
	# PSD plot
	#

	fig = plotpsd.plot_psds(psds, coinc_xmldoc, plot_width = 800)
	fig.tight_layout()

	filename = "%s_psd.%s" % (graceid, options.format)
	if options.no_upload:
		logging.info("writing %s ..." % filename)
		fig.savefig(filename)
	else:
		lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = filename, log_message = "strain spectral density plot", tagname = "psd")

	#
	# Cumulative SNRs plot
	#

	fig = plotpsd.plot_cumulative_snrs(psds, coinc_xmldoc, plot_width = 800)
	fig.tight_layout()

	filename = "%s_cumulative_snrs.%s" % (graceid, options.format)
	if options.no_upload:
		logging.info("writing %s ..." % filename)
		fig.savefig(filename)
	else:
		lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = filename, log_message = "cumulative SNRs plot", tagname = "psd")

	logging.info("finished processing %s" % graceid)
