#!/usr/bin/env python3
#
# Copyright (C) 2018 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 sys, os, glob, shutil, time
import re
import subprocess
import json

from optparse import OptionParser
from ligo.scald import report

ABOUT_URL = 'https://docs.google.com/document/d/12wJjCz8L1UczqRm86q3-EFnpnIZ2FHPSwKR_kym2L5g/pub?embedded=true'
SCHEDULE_URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vR1XwazhZYoVbMXFZCq_s2rlzyNwcF0xC4kyhnKrCeXFSWte-2jRodL590RU3PsoX4OVypYyAZ7Nl_8/pubhtml?widget=true&amp;headers=false'
IMAGE_URL = 'https://results.ligo.uwm.edu/~gstlalcbc/share/vis/gstlal.png'


def load_json(path):
	with open(path, 'r') as f:
		return json.loads(f.read())


def parse_command_line():
	parser = OptionParser(usage = "%prog [options] [file ...]", description = "%prog summary web page")
	parser.add_option("--webserver-dir", help = "Set the directory for the webserver.  Required.  Example /archive/home/channa/public_html/highmass_months_23-24_summary_page")
	parser.add_option("--open-box", action = "store_true", help = "Produce open box page")
	parser.add_option("--output-user-tag", action = "append", metavar = "name", help = "Set the basename for image search")
	parser.add_option("--title", default="gstlal_inspiral offline analysis")
	parser.add_option("--glob-path", help = "This is the path to search for images")

	opts, filenames = parser.parse_args()
	return opts, filenames


#
# Setup
#

opts, files = parse_command_line()
reportdir = opts.webserver_dir+'_lite'

thisreport = report.Report('gstlal analysis', image=IMAGE_URL)

try:
	os.makedirs(reportdir)
except OSError:
	pass

#
# Add the page tabs
#

summary = report.Tab('Summary')
about_doc = report.Tab('About', url=ABOUT_URL)
sched_doc = report.Tab('Schedule', url=SCHEDULE_URL)


#
# add page header
#

summary += report.Header('Summary')
summary += report.Description("This page was generated on %s by %s in the working directory: %s" % (time.strftime("%Y-%m-%d %H:%M"), os.environ["USER"], os.environ["PWD"]))


#
# IFAR, ln L plots and table
#

summary += report.Header('Rate vs. Threshold')
summary += report.Description("This section provides the detection statistic plots and a summary of the loudest event.")

summary += report.Header('Closed Box Results')
imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
summary += report.ImageGrid("Rate vs. Threshold", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_closedbox*.png'))

tabledata = load_json(os.path.join(opts.glob_path, '%sbgsummary_table.json' % opts.output_user_tag[0]))
summary += report.Table('Closed Box Summary Table').save(tabledata, reportdir)

if opts.open_box:
	summary += report.Header('Open Box Results')
	imgfooter = "Comparison of single time slide event rate to event rate expected from background as a function of threshold."
	summary += report.ImageGrid("Rate vs. Threshold", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*5_count_vs_*_openbox*.png'))
	
	tabledata = load_json(os.path.join(opts.glob_path, '%ssummary_table.json' % opts.output_user_tag[0]))
	summary += report.Table('Open Box Summary Table').save(tabledata, reportdir)

## Include found/missed as function of decisive characteristic SNR
summary += report.Header("Found / Missed Expected SNR")
summary += report.Description("""Measuring the found and missed injections as a function of various parameters aids in diagnosing the pipeline as well as providing the expected sensitivity of the pipeline to real signals.  The plots in this section show the missed and found injections for the various IFO times for coincident triggers.""")

tabledata = load_json(os.path.join(opts.glob_path, '%s_injection_summary.json' % opts.output_user_tag[0]))
footer = "Summary of missed and found injections broken up by detector time for %s" % opts.output_user_tag[0]
summary += report.Table('Injection Summary Table', footer=footer).save(tabledata, reportdir)

plots = os.path.join(opts.glob_path, '*%s*1_dec_expsnr_vs_mchirp_*.png' % opts.output_user_tag[0])
imgfooter = "Expected SNR of found and missed injections as a function of chirp mass: %s" % opts.output_user_tag[0]
summary += report.ImageGrid("Expected SNR vs. chirp mass", grid_size=4, footer=imgfooter).glob(plots)

## Include missed injection table
summary += report.Header("Missed Table")
tabledata = load_json(os.path.join(opts.glob_path, '%s_missed_summary.json' % opts.output_user_tag[0]))
summary += report.Table('Missed Injection Table for %s' % opts.output_user_tag[0]).save(tabledata, reportdir)


## Include search sensitivity binned by source type
summary += report.Header('Search Sensitivity')
summary += report.Description("""These plots characterize the overall sensitivity of the search. The detection rate is directly proportional to the observed sensitive volume, which is a function of the significance threshold used to identify candidates. These plots are useful for determining how sensitive the search was to the input injection population. Here we show the sensitivity as a function of source type: BNS mchirp between 0.8 and 2, NSBH between 2 and 4.5, BBH between 4.5 and 45.0, IMBH between 45.0 and 450.0""")

plots = os.path.join(opts.glob_path, '*%s*_BINNED_BY_SOURCE_TYPE*.png' % opts.output_user_tag[0])
imgfooter = "Binned by source type"
summary += report.ImageGrid("Sensitive volume (V*T) and mean sensitive distance: %s" % opts.output_user_tag[0], grid_size=4, footer=imgfooter, visible=False).glob(plots)

## Include horizon distance plots
imgfooter = "This is the distance at which you should see a 1.4 1.4 Msun binary at SNR 8. The first panel shows the time evolution of the horizon distance and the second panel shows the same information in histogram form."
summary += report.ImageGrid("Horizon distance", grid_size=1, footer=imgfooter).glob(os.path.join(opts.glob_path, '*HORIZON*.png'))

## Search summary
tabledata = load_json(os.path.join(opts.glob_path, '%s_plot_summary.json' % opts.output_user_tag[0]))
summary += report.Table('Search Summary').save(tabledata, reportdir)

## Include Chi-square distribution plots
summary += report.Header("Chi-squared Distributions")
summary += report.Description("The chi-squared test checks that the snr accumulated matches expectation.")

imgfooter = "Chi-squared vs snr for single detectors after coincidence.  Blue points are full data zero lag, red are software injections and black are time slides."
summary += report.ImageGrid("Chi-squared Distributions", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*closedbox*.png'))
if opts.open_box:
	summary += report.ImageGrid("Chi-squared Distributions: Zero lag", grid_size=3, footer=imgfooter).glob(os.path.join(opts.glob_path, '*3_chi2_vs_rho_*openbox*.png'))

thisreport += summary
thisreport += about_doc
thisreport += sched_doc

#
# write the result
#

thisreport.save(reportdir, config_name='report_lite')
