#!/usr/bin/env python
#
# Copyright (C) 2013,2016,2018-2019,2022-2024
# Smithsonian Astrophysical Observatory
#
# 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.
#

toolname = "obsid_search_csc"
__revision__ = "15 July 2024"

import sys
import os

import ciao_contrib.logger_wrapper as lw
lw.initialize_logger(toolname)
lgr = lw.get_logger(toolname)
verb0 = lgr.verbose0
verb1 = lgr.verbose1
verb2 = lgr.verbose2
verb3 = lgr.verbose3
verb5 = lgr.verbose5

import ciao_contrib.cda.csccli as csc
from ciao_contrib.param_soaker import *
import stk as stk


def parse_inputs( pars ):
    """
    Parse parameter inputs
    """
    retval = {}

    retval["obsid"] = ",".join( stk.build(pars["obsid"]))

    if not all( [x.isdigit() for x in retval["obsid"].split(",")]):
        raise ValueError("obsid must be a list of individual integers")
    
    if "INDEF" == pars["columns"] or len(pars["columns"]) == 0:
        retval["columns"] = csc.get_default_columns(pars["catalog"])
    else:
        retval["columns"] = stk.build( pars["columns"] )
        retval["columns"] = csc.check_required_names( retval["columns"], pars["catalog"] )

    if 'none' == pars["outfile"].lower():
        retval["outfile"] = None
    else:
        retval["outfile"] = pars["outfile"]

    # ~ ## TODO: eventually replace with actual token
    # ~ if "csc2" == pars["catalog"]:
        # ~ pars["catalog"] = "csc2"
    #~ if "csc2" == pars["catalog"] and "none" != pars["download"]:
        #~ pars["download"] = "none"
        #~ verb0("WARNING: files cannot yet be retrieved using the current catalog release")
    
    if "none" == pars["download"]:
        retval["getfiles"] = False
        retval["myfiles"] = None
        retval["mybands"] = None
        retval["root"] = None
    else:
        retval["getfiles"] = pars["download"]
        retval["root"] = pars["root"]

        if len(pars["filetypes"] ) == 0:
            # if filetypes is blank, use all of them 
            retval["myfiles"] = ",".join( csc.fileTypes[pars["catalog"]].keys() )
        else:
            retval["myfiles"] = csc.check_filetypes( pars["filetypes"], pars["catalog"] )
            if len(retval["myfiles"]) == 0:
                raise ValueError("No recognized file types supplied")
        
        if len(pars["bands"]) == 0:
            # if bands is blank, use all of them
            retval["mybands"] = ",".join(csc.all_bands())
        else:
            retval["mybands"] = csc.check_bandtypes( pars["bands"] )
            if len(retval["mybands"]) == 0:
                raise ValueError("No recognized energy band supplied")

    
    retval["clobber"] = ( pars["clobber"] == "yes" )
    retval["catalog"] = pars["catalog"]
    
    return retval


#
# Main Routine
#
@lw.handle_ciao_errors( toolname, __revision__)
def main():
    """
    """
    # get parameters
    pars = get_params(toolname, "rw", sys.argv, 
      verbose={"set":lw.set_verbosity, "cmd":verb1} )
    pp = parse_inputs( pars )

    # check clobber before query
    from ciao_contrib._tools.fileio import outfile_clobber_checks
    outfile_clobber_checks( pars["clobber"], pars["outfile"] )

    #
    # Query catalog by position
    #
    mypage = csc.search_src_by_obsid( pp["obsid"], pp["columns"], pp["catalog"] )
    csc.save_results( mypage, pp["outfile"], pp["clobber"] )    

    #
    # Print results
    #
    mysrcs = csc.parse_csc_result( mypage )
    xtra = csc.extra_cols_to_summarize( mysrcs, pars["columns"], pp["catalog"])
    csc.summarize_results( mysrcs, extracols=xtra )
    
    #
    # Retrieve the files if asked
    # 
    if pp["getfiles"]:
        csc.retrieve_files( mysrcs, pp["root"], pp["myfiles"], pp["mybands"], pp["getfiles"], pp["catalog"], byObi=True )


if __name__ == "__main__":
    try:
        main()
    except Exception as E:
        print("\n# "+toolname+" ("+__revision__+"): ERROR "+str(E)+"\n", file=sys.stderr)
        sys.exit(1)
    sys.exit(0)
    
