#!/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 missed injection"""
import h5py, argparse, pycbc.version, pycbc.results, sys
import numpy, pycbc.pnutils

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('--output-file')
parser.add_argument('--injection-file', required=True,
    help="The HDF format injection file. Required")
parser.add_argument('--injection-index', type=int, required=True,
    help="The index of the injection to print out. Required")
parser.add_argument('--n-nearest', type=int, 
    help="Optional, used in the title")

args = parser.parse_args()

f = h5py.File(args.injection_file, 'r')
iidx = args.injection_index

# make a table for the coincident information #################################
params = []
headers = []
data = []

labels = {
    'end_time': 'End&nbsp;time',
    'dec_chirp_dist': 'Dec.&nbsp;chirp dist',
    'eff_dist_h'    : 'D<sub>eff</sub>&nbsp;H',
    'eff_dist_l'    : 'D<sub>eff</sub>&nbsp;L',
    'mass1'      : 'm<sub>1</sub>',
    'mass2'      : 'm<sub>2</sub>',
    'mchirp'     : 'M<sub>c</sub>',
    'eta'        : '&eta;',
    'longitude'  : 'RA',
    'latitude'   : 'Dec',
    'inclination': '&iota;',
    'spin1x': 's<sub>1x</sub>',
    'spin1y': 's<sub>1y</sub>',
    'spin1z': 's<sub>1z</sub>',
    'spin2x': 's<sub>2x</sub>',
    'spin2y': 's<sub>2y</sub>',
    'spin2z': 's<sub>2z</sub>'
}

params += ['end_time']

if 'optimal_snr_1' in f['injections'].keys():
    labels['optimal_snr_1'] = 'Opt.&nbsp;SNR %s' % f.attrs['detector_1']
    labels['optimal_snr_2'] = 'Opt.&nbsp;SNR %s' % f.attrs['detector_2']
    params += ['optimal_snr_1', 'optimal_snr_2']
elif 'ifos' in f.attrs:
    ifolist = f.attrs['ifos'].split(' ')
    for ifo in ifolist:
        labels['optimal_snr_%s' % ifo] = 'Opt.&nbsp;SNR %s' % ifo
        params += ['optimal_snr_%s' % ifo]
else:
    params += ['dec_chirp_dist', 'eff_dist_h', 'eff_dist_l']
    dec_dist = max(f['injections']['eff_dist_h'][iidx], f['injections']['eff_dist_l'][iidx])
    dec_chirp_dist = pycbc.pnutils.chirp_distance(dec_dist, mchirp)

params += ['mass1', 'mass2', 'mchirp', 'eta', 'longitude', 'latitude',
            'inclination', 'spin1x', 'spin1y', 'spin1z', 'spin2x', 'spin2y',
            'spin2z']

m1, m2 = f['injections']['mass1'][iidx], f['injections']['mass2'][iidx]
mchirp, eta = pycbc.pnutils.mass1_mass2_to_mchirp_eta(m1, m2)

for p in params:
    headers += [labels[p]]

    if p in f['injections']:
        data += ["%.2f" % f['injections'][p][iidx]]
    elif p == 'mchirp':
        data += ["%.2f" % mchirp]
    elif p == 'eta':
        data += ["%.2f" % eta]
    elif p == 'dec chirp dist':
        data += ["%.2f" % dec_chirp_dist]

table = numpy.array([data], dtype=str)
html = str(pycbc.results.static_table(table, headers))

tag = ''
if args.n_nearest is not None:
    tag = ':%s' % (args.n_nearest + 1)

pycbc.results.save_fig_with_metadata(html, args.output_file, {},
                        cmd = ' '.join(sys.argv),
                        title = 'Parameters of missed injection' + tag,
                        caption = "Parameters of this injection")
   
