#!python

#
# Project Librarian: Alex Urban
#              Graduate Student
#              UW-Milwaukee Department of Physics
#              Center for Gravitation & Cosmology
#              <alexander.urban@ligo.org>
#
# 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, see <http://www.gnu.org/licenses/>.
#

"""
Script that scours all event candidates in a given period from a local cache
of GCN Notices, then saves them in a CSV-style table. (It is assumed that event
portfolios are named as [OBSERVATORY]_[DATE]_[TIME (UTC)]_[TRIGGER ID].)
"""
__author__ = "Mark Poe <mark.poe@ligo.org>, Alex Urban <alexander.urban@ligo.org>"


# Imports.
import os
from lal.gpstime import tconvert
from optparse import Option, OptionParser


# Command line options.
parser = OptionParser(
    description = __doc__,
    usage = "%prog [options]",
    option_list = [
        Option("-s", "--start-time", metavar='"YYYY-MM-DD HH:MM:SS.SS"', default=None,
            help="UTC start time string in ISO 8601 format (required)"),
        Option("-e", "--end-time", metavar='"YYYY-MM-DD HH:MM:SS.SS"', default="now",
            help="UTC end time string in ISO 8601 format (default: %default)"),
        Option("-o", "--output", metavar="FILENAME.csv", default="/dev/stdout",
            help="Name of output file in which to store results of the query (default: %default)"),
        Option("-c", "--event-cache", metavar="/path/to/local/cache", default=None,
            help="Path to the GCN event cache on the local filesystem (required)")
    ])
opts, args = parser.parse_args()


# Check for missing required arguments.
missing = []
for option in parser.option_list:
    if 'required' in option.help and eval('opts.' + option.dest) == None:
        missing.extend(option._long_opts)
if len(missing) > 0:
    parser.error('Missing required options: {0}'.format(str(missing)))


# Construct a query around certain GPS times.
start = float(tconvert( opts.start_time ))
end = float(tconvert( opts.end_time ))

# Fetch the full list of event portfolios in the local cache.
portfolios = os.listdir( opts.event_cache )

# Keep event portfolios from this list if and only if they fall
# within the specified time window.
data = [('Observatory', 'Date', 'Time (UTC)', 'Trigger No.')]
for portfolio in portfolios:
    try:
        obs, date, time, trigID = portfolio.split('_')
        gps_time = float(tconvert( '{0} {1}'.format(date, time) ))
        if gps_time > start and gps_time < end:
            data.append( (obs, date, time, trigID) )
    except:
        import sys
        sys.stderr.write( 'WARNING: Portfolio {0} does not have the expected format.\n'.format( portfolio ))
        pass

# Save to file.
with open(opts.output, 'w') as f:
    for row in data: f.write( "%s\n" % "\t".join(row) )
