#! /usr/bin/env python3
# -*- coding: iso-8859-15 -*-

from gravi_download import newquery, RunError
from optparse import OptionParser
from gravi_download.log import Log, NOTICE
import sys

log = Log()
usage = """
        usage:  %prog [options] night [night2, night3, night4, ...]
                %prog [options] -s startdate -e enddate

        where night is the night of the form yyyy-mm-dd

        Return the file path list to STDOUT  
"""
parser = OptionParser(usage)
parser.add_option("-o", "--output_dir", dest="output_dir",
                  help="Output directory")

parser.add_option("-l", "--username", dest="username",
                  help="Eso Portal user name")


parser.add_option("-s", "--stime", dest="stime",  metavar="START_DATE", 
                  help="""Start time 
                            float (in hour) or format Thh, Thh:mm or Thh:mm:ss     
                          -or- full date stamp if no night parsed :e.g. 2015-10-13T12""")

parser.add_option("-e", "--etime", dest="etime", metavar="END_DATE", 
                  help="""End time 
                            float (in hour) or format Thh, Thh:mm or Thh:mm:ss
                          -or- full date stamp if no night parsed :e.g. 2015-10-14T12""")

parser.add_option("-i", "--instrument", dest="instrument",
                  help="change the default 'GRAVITY' instrument name")

parser.add_option("-f", "--file", dest="file",
                  help="output file containing the list of downloaded file default is ./gravi_download.lst")

parser.add_option("-r", "--request", dest="request",metavar="request-number(s)", 
                  help="looks only on that specified request, can be a list with space separators")



parser.add_option("-a", action="store_true", dest="listreq",
                  help="print the list of request numbers in stdout. nothing else is done !")



parser.add_option("-d", action="store_true", dest="debug",
                  help="turn on debug mode, no files are downloaded")




if __name__ == "__main__":
    (options, args) = parser.parse_args()

    if not options.listreq and not len(args) and ((options.stime is None) or (options.etime is None)):
        if options.request:
            request =  [r for r in options.request.split(" ")  if r]
            options.stime = "1970-01-01T12:00:00"
            options.etime = "2050-01-01T12:00:00"    
        else:    
            parser.print_help()
            print ("If not nights are given : 1) both options  -s strart_date -e end_date must be provided 2) -r request number must be provided")
            quit()
    if not len(args):
        args = [None]        
    file_name = options.file or "./gravi_download.lst"
    try:
        fout = open(file_name, "w")
    except IOError as e:
        sys.stderr.write("\nERROR: %s\n\n"%e.message)
        quit(1)
        
    one_success = False  
    request = options.request
    if request:
        request = [r for r in request.split(" ")  if r]

    
    if options.listreq:
        q = newquery('2015-10-13', # dummy night does not matter                     
                     USERNAME=options.username, instrument=options.instrument, debug=options.debug)                    
        sys.stdout.write(" ".join(q._query_request())+"\n")
        quit(0)


    for night in args:    
        try:    
            q = newquery(night, stime=options.stime, etime=options.etime, output_dir=options.output_dir, 
                         USERNAME=options.username, instrument=options.instrument, debug=options.debug)
            r = q.query(request=request)

        except RunError as e:
            print(e)
            sys.stderr.write("\nERROR: %s\n\n"%e.message)
            quit(2)
            
        if r is not None:
            one_success = True
            for f in q.download():
                fout.write("%s\n"%f)
    if one_success:            
        log.log("List file result in %s"%file_name, 1, NOTICE)            

