#!/usr/bin/env python
# 
#  Copyright (C) 2005-2008,2010,2013,2015-2016,2022  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.
#


# (12/2010) - convert to python 

import os
import sys
import glob
import paramio
import string

'''Use the history module to add HISTORY records to crate'''
from pycrates import read_file 
from pycrates import add_history, CrateKey
from history import HistoryRecord


##  get parameters
#
def get_params( toolpar ) :
   pp = {}
   try :
      pfile = paramio.paramopen(toolpar, "rw", sys.argv)
   except :
      error_out("ERROR: can't open parameter file "+toolpar )
   pp["infile"] = paramio.pgetstr(pfile,"infile")
   pp["refsrcfile"] = paramio.pgetstr(pfile,"refsrcfile")
   pp["updfile"] = paramio.pgetstr(pfile,"updfile")
   pp["outfile"] = paramio.pgetstr(pfile,"outfile")
   pp["wcsfile"] = paramio.pgetstr(pfile,"wcsfile")
   pp["radius"] = paramio.pgetstr(pfile,"radius")     
   pp["residlim"] = paramio.pgetstr(pfile,"residlim")
   pp["residfac"] = paramio.pgetstr(pfile,"residfac")
   pp["residtype"] = paramio.pgetstr(pfile,"residtype")
   pp["method"] = paramio.pgetstr(pfile,"method")
   pp["logfile"] = paramio.pgetstr(pfile,"logfile")
   pp["clobber"] = paramio.pgetstr(pfile,"clobber")
   pp["verbose"] = paramio.pgetstr(pfile,"verbose")
   pp["mode"] = paramio.pgetstr(pfile,"mode")
   paramio.paramclose(pfile)
   return pp

## display message
#
def display_msg( msg ) :
    sys.stderr.write( msg )
    sys.stderr.flush()

## error out w/ message
#
def error_out( msg ) :
    display_msg( msg )
    sys.exit(1)

## if clobber is yes and the outfile exists, error out.
#
def check_clob( Clob, File ) :
   if ( Clob[0] == "n") or ( Clob[0] == "N") :
      if os.path.exists( File ) == True :
         msg="\nERROR: outfile '"+File+"' exists and clobber=no.\n"
         error_out(msg)

## execute task (cmd); if there's a problem, error_out w/ message 
#
def exe_task ( pp ) :
   # ------ wcs_match cmd
   cmd = "wcs_match  infile='"+pp["infile"]+"' refsrcfile='"+pp["refsrcfile"]
   cmd += "' outfile=-   wcsfile='"+pp["wcsfile"]
   cmd += "' logfile=stderr   radius="+pp["radius"]
   if ( pp["method"] != "default" ) :
      cmd += " method="+pp["method"]
   cmd += " residlim="+pp["residlim"]+" residfac="+pp["residfac"]
   cmd += " residtype="+pp["residtype"]+" clobber="+pp["clobber"]
   cmd += " verbose="+pp["verbose"]+" mode="+pp["mode"]

   # ------ pipe output of wcs_match (outfile) to wcs_update
   cmd += " | wcs_update  infile='"+pp["updfile"]+"' outfile='"+pp["outfile"]
   cmd += "' transformfile=-   wcsfile=   logfile='"+pp["logfile"]
   cmd += "' deltax=0   deltay=0   rotang=0  scalefac=1"
   cmd += " clobber="+pp["clobber"]+" verbose="+pp["verbose"]
   cmd += " mode="+pp["mode"]

   if ( int(pp["verbose"]) > 1 ) :
      display_msg("\nreproject_aspect cmd_str is: "+cmd+"\n" )

   paramio.punlearn( "wcs_match" )
   paramio.punlearn( "wcs_update" )
   status = os.system ( cmd )
   if status != 0  :
      error_out("ERROR: problem to run wcs_match and wcs_update.\n")
   #else :
      #sys.exit(0)
#end: exe_task

def add_history_to_file(file_name, tool_name, param_names, param_values):
   if os.path.exists( file_name) == False : 
      return 
   crate = read_file(file_name, mode="rw")
    
   histnum = crate.get_key("HISTNUM")
   if histnum is None:
      histnum = CrateKey()
      histnum.name = "HISTNUM"
      histnum.value = 1
      crate.add_key(histnum)
        
   startat = histnum.value
   startat = 1 if startat is None else startat

   hh = HistoryRecord(tool=tool_name,param_names=param_names,
                      param_values=param_values, asc_start=startat)    
   add_history(crate, hh) 
    
   # Increment HISTNUM for new lines
   hlen = hh.as_ASC_FITS().split("\n")
   histnum.value = startat+len(hlen)

   crate.write() 
#end: add_history_to_file  


# ------------ main code --------------
#
def main() :

   ##  get parameters 
   pp = get_params( "reproject_aspect" )

   ##  check clobber 
   check_clob( pp["clobber"], pp["outfile"] ) 

   ##  exe task 
   exe_task( pp )

   ## add history 
   # Get parameter name/values in order stored in parameter file
   pnames = paramio.plist("reproject_aspect") 
   pvals = [pp[x] for x in pnames]
   if len(pp["outfile"].strip(" ")) == 0 :    # blanks
      add_history_to_file( pp["updfile"], "reproject_aspect", pnames, pvals)
   else : 
      add_history_to_file( pp["outfile"], "reproject_aspect", pnames, pvals)

   sys.exit(0)

if __name__=="__main__":
    main()
