#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2021  ChiWai Chan
#
# 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.

"""Plot horizon history from ranking statistics.

"""

from itertools import groupby
import os
from optparse import OptionParser
from pathlib import Path

from gstlal.plots import set_matplotlib_cache_directory
set_matplotlib_cache_directory()
from gstlal.plots import horizon

from lal.utils import CacheEntry

def parse_command_line():
	usage = "Usage: %prog [options] file1 file2 ..."
	parser = OptionParser(description = __doc__, usage = usage)

	parser.add_option("-o", "--outdir", default = ".", help = "Set the output directory. By default, current directory will be used.")
	parser.add_option("-f", "--format", default = "png", help = "Set the output format. By default, the output will be a png file.")
	parser.add_option("-s", "--fig-size", default = "12,4", help = "Set the output figure size in inch. By default, the figure size will be 12,4. (Optional)")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose. (Optional)")

	options, args = parser.parse_args()
	options.format = options.format.strip(".")
	try:
		figsize = options.fig_size.split(",")
		w, h = float(figsize[0]), float(figsize[1])
	except:
		raise ValueError("Please provide valid --fig-size, expecting a format of 'width,height', got '%s'." % options.fig_size)
	else:
		options.fig_size = (w, h)


	if len(args) == 0:
		raise ValueError("Must provide at least one ranking statistics file.")

	return options, args

options, files = parse_command_line()

# Create output directory if needed
os.makedirs(options.outdir, exist_ok=True)

urls = []
for f in files:
	if f.endswith(".cache"):
		urls.extend([CacheEntry(line).url for line in open(f)])
	elif f.endswith(".gz"):
		urls.append(f)

outdir = Path(options.outdir)
for key, group in groupby(sorted(urls, key = lambda x: CacheEntry.from_T050017(x).description), lambda x: CacheEntry.from_T050017(x).description):
	rankfiles = list(group)
	ce = CacheEntry.from_T050017(rankfiles[0])
	title = f"Horizon Distance for Bin {ce.description.replace('_MARG_DIST_STATS', '')}"
	desc = ce.description.replace('MARG_DIST_STATS', 'HORIZON')
	start = ce.segment[0]
	duration = ce.segment[1] - ce.segment[0]
	output = outdir / f"{ce.observatory}-{desc}-{start}-{duration}.{options.format}"
	horizon_distance = horizon.HorizonDistance.from_rankingstats(rankfiles, verbose = options.verbose)
	horizon_distance.savefig(output, figsize = options.fig_size, title = title)
