#!/usr/bin/env python3
"""
Plotter for gstlal_inspiral_calc_snr
"""
from optparse import OptionParser
import numpy
import os
import sys

from gstlal import svd_bank_snr
from gstlal.plots import snr as plotsnr

from lal.utils import CacheEntry

def parse_command_line():
	parser = OptionParser(description = __doc__)

	parser.add_option("-o", "--outdir", metavar = "directory", help = "The output directory for the SNR plot (require).")
	parser.add_option("-i", "--input", metavar = "cache", help = "The input cache containing SNR urls (require).")
	parser.add_option("-f", "--format", metavar = "file_type", help = "The format of the output plot (default = .png).")
	parser.add_option("--center", metavar = "gpsSeconds", type = "float", help = "Center the plot to --center (optional).")
	parser.add_option("--width", metavar = "inch", default = 8, type = "int", help = "The output width of the figure.")
	parser.add_option("--span", metavar = "seconds", type = "float", help = "The time span around --center (optional).")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")

	options, args = parser.parse_args()

	if options.input is None:
		raise ValueError("Missing --input.")
	if options.outdir is None:
		raise ValueError("Missing --outdir.")
	if options.center is not None and options.span is None:
		raise ValueError("--span should also be provided if --center is provided.")
	if options.span is not None and options.center is None:
		raise ValueError("--center should also be provided if --span is provided.")

	return options

options = parse_command_line()

suffix = ".png" if (options.format is None) else options.format
urls = []
description = None
segment = None
with open(options.input) as cache:
	for line in cache.readlines():
		entry = CacheEntry(line)
		urls.append(entry.url)
		if description is None and segment is None:
			description = entry.description
			segment = "-" + str(entry.segment[0]) + "-" + str(entry.segment[1] - entry.segment[0])
		else:
			assert description + segment == entry.description + "-" + str(entry.segment[0]) + "-" + str(entry.segment[1] - entry.segment[0]), "Cannot plot snrs with different segments or for different template."

# done checking file consistency, overwrite output name with customized segment
if options.center and options.span:
	segment = "-" + str(int(options.center - options.span)) + "-" + str(int(options.span * 2))

SNRs_dict = {}
autocorrelations_dict = {}
for url in urls:
	snr_dict, ac_dict = svd_bank_snr.read_xmldoc(svd_bank_snr.read_url(url, svd_bank_snr.SNRContentHandler, verbose = options.verbose))
	SNRs_dict.update(snr_dict)
	autocorrelations_dict.update(ac_dict)
snrs_groups = zip(*SNRs_dict.values())
acs_groups = zip(*autocorrelations_dict.values())

#=============================================================================================
#
#					Plot SNRs
#
#=============================================================================================
for snrs_group in snrs_groups:
	figure = plotsnr.plot_snr(dict(zip(SNRs_dict.keys(), zip(snrs_group))), width = options.width, center = options.center, span = options.span, verbose = options.verbose)
	if len(zip(*SNRs_dict.values())) == 1:
		figure.savefig(os.path.join(options.outdir, "%s-" % "".join(sorted(SNRs_dict.keys())) + description + segment + suffix))
	else:
		figure.savefig(os.path.join(options.outdir, "%s-" % "".join(sorted(SNRs_dict.keys())) + description.replace("ALL_ALL", "_".join(snrs_group[0].name.split("_")[1:3])) + segment + suffix))


if len(snrs_groups) != len(acs_groups):
	raise ValueError("The number of SNR time series and template autocorrelations does not matched.")

#=============================================================================================
#
#				Plot SNRs with autocorrelation
#
#=============================================================================================
# This is only useful when SNRs are complex time series.
if numpy.iscomplexobj(SNRs_dict.values()[0][0].data.data):
	row = 0
	for snrs_group, acs_group in zip(snrs_groups, acs_groups):
		figure = plotsnr.plot_snr_with_ac(dict(zip(SNRs_dict.keys(), zip(snrs_group))), dict(zip(autocorrelations_dict.keys(), zip(acs_group))),  width = options.width, ref_trigger_time = options.center, verbose = options.verbose)

		all_instruments = set(SNRs_dict) & set(autocorrelations_dict)
		# just pick one, they must be the same length
		if len(zip(*SNRs_dict.values())) == 1:
			figure.savefig(os.path.join(options.outdir, "%s-" % "".join(sorted(all_instruments)) + description + "_with_autocorrlation" + segment+ suffix))
		else:
			figure.savefig(os.path.join(options.outdir, "%s-" % "".join(sorted(all_instruments)) + description.replace("ALL_ALL", "_".join(snrs_group[0].name.split("_")[1:3])) + "_with_autocorrlation" + segment + suffix))
		row += 1
