#! /usr/bin/env python3
# -*- coding: iso-8859-15 -*-
"""
Created on Sun May 24 22:56:25 2015

@author: kervella
"""

# ATTENTION: necessary to install the reportlab and pdfrw libraries

#==============================================================================
# MAIN GRAVITY QUALITY REPORT PROGRAM    
#==============================================================================

import os
import sys
import traceback
try:
   import pyfits
except:
   from astropy.io import fits as pyfits
import gravi_visual
from glob import glob
from optparse import OptionParser

# Add options
usage = """
        usage:  %prog
"""
parser = OptionParser(usage)
parser.add_option("-o","--overwrite", action="store_true", dest="overwrite_flag", default=False,
                  help="Overwrite existing PDFs")

(argoptions, args) = parser.parse_args()

filelist=[]
## If the user specifies a file name or wild cards ("*_0001.fits")
if len(sys.argv) > 1 :
    longnames = [f for files in sys.argv[1:] for f in glob(files)]
    filelist = [os.path.splitext(f)[0] for f in longnames]
## Processing of the full current directory
else :
    for file in os.listdir("."):
        if file.endswith(".fits"):
            filelist.append(os.path.splitext(file)[0])

filelist.sort() # process the files in alphabetical order
    
for filename in filelist:
    fullname = os.getcwd()+'/'+filename
    gravi_file=pyfits.open(fullname+'.fits', mode='readonly')
    header = gravi_file[0].header
    
    if 'INSTRUME' in header: # only GRAVITY standard files are taken into account
        if 'GRAV' in header['INSTRUME']:
            try:        
                if 'HIERARCH ESO PRO TYPE' in header:
                    datatype = header['HIERARCH ESO PRO TYPE']
                    print(('datatype=%s'%datatype))
                
                if 'HIERARCH ESO PRO CATG' in header:
                    datacatg = header['HIERARCH ESO PRO CATG']
                    print(('datacatg=%s'%datacatg))
                
                if 'HIERARCH ESO DPR CATG' in header:
                    dprcatg = header['HIERARCH ESO DPR CATG']
                
                #for hdu in gravi_file:
                #    if hdu.name == 'PROFILE_DATA':
                #        datacatg = 'PROFILE'

                if (datatype == 'REDUCED') and ("P2VMRED" in datacatg):
                    # P2VM reduced data files (interferometric quantities function of time)
                    print((' Creating vibration report for P2VMREDUCED file: '+filename+'.fits'))
                    if os.path.isfile(fullname+"-VIBRATIONS.pdf") and argoptions.overwrite_flag==False:
                        print ('  output PDF already exists, skip...')
                        continue
                    p2vmreduced = gravi_visual.P2vmreduced(fullname+'.fits')
                    gravi_visual.produce_vibrations_report(p2vmreduced,filename)
                
            except Exception:
                print((traceback.format_exc()))
                print((' Fail to create vibrations report for file: '+filename+'.fits... continue'))
                continue
                
