#!/bin/env python
# Copyright (C) 2015 Alexander Harvey Nitz
#
# 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 3 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.
""" Make tables describing a coincident foreground event"""
import h5py, argparse, logging, pycbc.version, pycbc.events, pycbc.results, sys
import matplotlib; matplotlib.use('Agg'); import pylab
import numpy, pycbc.pnutils, lal, datetime


def get_summary_page_link(ifo, utc_time):
    """ Return a string that links to the summary page for this ifo """
    search_form = """<form name="%s_alog_search" id="%s_alog_search" method="post">
<input type="hidden" name="srcDateFrom" id="srcDateFrom" value="%s" size="20" />
<input type="hidden" name="srcDateTo" id="srcDateTo" value="%s" size="20" />
</form>
"""
    data = {'H1':"""H1&nbsp;<a href=https://ldas-jobs.ligo-wa.caltech.edu/~detchar/summary/day/%s>Summary</a>&nbsp;<a onclick="redirect('h1_alog_search','https://alog.ligo-wa.caltech.edu/aLOG/includes/search.php?adminType=search'); return true;">aLOG</a>""",
            'L1':"""L1&nbsp;<a href=https://ldas-jobs.ligo-la.caltech.edu/~detchar/summary/day/%s>Summary</a>&nbsp;<a onclick="redirect('l1_alog_search','https://alog.ligo-la.caltech.edu/aLOG/includes/search.php?adminType=search'); return true;">aLOG</a>""" }
    if ifo not in data:
        return ifo
    else:
        euro_utc = '%02d-%02d-%4d' % (utc_time[1], utc_time[2], utc_time[0])
        ext = '%4d%02d%02d' % (utc_time[0], utc_time[1], utc_time[2]) 
        return_string = search_form % (ifo.lower(), ifo.lower(), euro_utc, euro_utc)
        return_string += data[ifo] % ext
        return return_string


parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version',
    version=pycbc.version.git_verbose_msg)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--single-trigger-files', nargs='+', 
              help="HDF format single detector trigger files for the full data run")
parser.add_argument('--bank-file',
              help="HDF format template bank file")
parser.add_argument('--output-file')
parser.add_argument('--statmap-file',
    help="The HDF format clustered coincident statmap file containing the result "
         "triggers. ")
parser.add_argument('--n-loudest', type=int,
    help="The trigger Nth loudest trigger to examine, use with statmap file")

args = parser.parse_args()
pycbc.init_logging(args.verbose)

# Get the nth loudest trigger from the output of pycbc_coinc_statmap
f = h5py.File(args.statmap_file, 'r')
try:
    n = f['foreground/stat'][:].argsort()[::-1][args.n_loudest]
except:
    f = open(args.output_file, 'w')
    f.write("<h1>Event %s, no triggers found</h1>" % (args.n_loudest + 1))
    f.close()
    sys.exit()

d = f['foreground']

# JavaScript for searching the aLOG
html = """<script type="text/javascript">
function redirect(form,way)
{
        // Set location to form and submit.
        if(form != '')
        {
                document.forms[form].action=way;
                document.forms[form].submit();
        }
        else
        {
                window.top.location = way;
        }
}
</script>"""

# make a table for the coincident information #################################
headers = ["Combined Ranking Stat.", "Inc. IFAR (yrs)","Inc. FAP (yrs)", 
                      "exc. IFAR (yrs)", "exc. FAP (yrs)", "Time Delay (s)"]

table = numpy.array([
                     ['%5.2f' % d['stat'][:][n], 
                      '%5.2f' % d['ifar'][:][n], 
                      '%5.2e' % d['fap'][:][n],
                      '%5.2f' % d['ifar_exc'][:][n], 
                      '%5.2e' % d['fap_exc'][:][n],
                      '%5.4f' % (d['time2'][:][n] - d['time1'][:][n])]
                    ], dtype=str)
html += str(pycbc.results.static_table(table, headers))

# make a table for the single detector information ############################
headers = ["Detector&nbsp;Status", "UTC", "Time", "SNR", "NewSNR", "Chisq", "Bins",
           "Phase", "M1", "M2", "Mc", "S1z", "S2z", "Duration"]

ifo1, ifo2 = f.attrs['detector_1'], f.attrs['detector_2']
idx = {ifo1:d['trigger_id1'][:][n], ifo2:d['trigger_id2'][:][n]}


# Store the single detector trigger files keyed by ifo in a dictionary
table = []
files = {}
for fname in args.single_trigger_files:
    f = h5py.File(fname, 'r')
    ifos = f.keys()
    for ifo in ifos:
        files[ifo] = f[ifo]

bank = h5py.File(args.bank_file, 'r')

for ifo in files.keys():
    d = files[ifo]
    i = idx[ifo]
    tid = d['template_id'][:][i]
    rchisq =  d['chisq'][:][i] / (d['chisq_dof'][:][i] * 2 - 2)
    mchirp = (pycbc.pnutils.mass1_mass2_to_mchirp_eta(bank['mass1'][:][tid], 
                                                      bank['mass2'][:][tid]))[0]  
                                                      
    time = d['end_time'][:][i]
    utc = lal.GPSToUTC(int(time))[0:6]
                                                                            
    data = [get_summary_page_link(ifo, utc),
            str(datetime.datetime(*utc)),
            time,
            '%5.2f' % d['snr'][:][i],
            '%5.2f' %  pycbc.events.newsnr(d['snr'][:][i], rchisq),
            '%5.2f' %  rchisq,            
            '%5.2f' %  d['chisq_dof'][:][i],
            '%5.2f' % d['coa_phase'][:][i],
            '%5.2f' % bank['mass1'][:][tid],
            '%5.2f' % bank['mass2'][:][tid],
            '%5.2f' % mchirp,
            '%5.2f' % bank['spin1z'][:][tid],
            '%5.2f' % bank['spin2z'][:][tid],
            '%5.2f' % d['template_duration'][:][i],
           ]
    table.append(data)    

html += str(pycbc.results.static_table(table, headers))
###############################################################################

pycbc.results.save_fig_with_metadata(html, args.output_file, {},
                        cmd = ' '.join(sys.argv),
                        title = 'Parameters of Coincident Event Ranked %s' % (args.n_loudest + 1),
                        caption = 'Parameters of the event ranked number %s by the search. The figures below show the mini-followup data for this event.' % (args.n_loudest + 1))
