# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/data_mgr/create_empty_FITS.py 3180 2020-06-18 10:24:21Z depa $

"""Creates an empty FITS file, with only CHECKSUM and DATESUM keywords
The Header will be filled during operation by callto printFITS  ICE method
data will be included from original file with a call to populateWithData ICE method

This script is called by C++ method it expect,
inFilename: as the input file name to be formatted adding date, counter and instrument mode
instrumentMode: wich is optional

It saves in global namespace
status
outFilename

wich will be used by the embedding C++ caller"""

from astropy.io import fits
import time
from datetime import datetime
import pandas
# from util import shinsLogger
import sys
import os
import Ice

 # provided by caller either in fitsFilename or as
insroot = os.getenv("INSROOT")
dataDir = "/data/fits/"
# input variable
if "instrumentMode" not in globals():
    insMode = "calib" # instrumentMode can assume values: science | calib | monit

dfHCards = pandas.read_csv(dataDir+'keyword_list.csv',sep=',', encoding='cp1252', header=0)
listHCards = [tuple(r) for r in dfHCards.to_numpy()]
listHCardsMandatory = listHCards[0:8]
listHCardsBasicLBT  = listHCards[8:47]
listHCardsTelescope = listHCards[47:70]
listHCardsM1        = listHCards[70:76]
listHCardsM2        = listHCards[76:82]
listHCardsIntrument = listHCards[82:186]
listHCardsDet       = listHCards[186:234]
listHCardsWCS       = listHCards[234:253]
listHCardsWCSSPec   = listHCards[253:270]
listHCardsEnv       = listHCards[270:]
try:
    hdu = fits.PrimaryHDU()
    hdu.append(listHCardsMandatory[-1])
    hdu.extend(cards=listHCardsBasicLBT)
    UTCCurrentTime = datetime.utcnow() #time.gmtime()
    if not os.path.exists(dataDir+"running_index.txt"):
        f = open(dataDir+"running_index.txt", "w")
        f.close()
        counter = 0
    else:
        with open(dataDir+"running_index.txt", "r") as f:
            counter = f.read()[0:]
    print (inFilename, counter)
    fitsDir = \
        dataDir+"merged/{:0>4d}/{:0>2d}/{:0>2d}/".format(
            #UTCCurrentTime.tm_year, UTCCurrentTime.tm_mon, UTCCurrentTime.tm_mday)
            UTCCurrentTime.year, UTCCurrentTime.month, UTCCurrentTime.day)

    if not os.path.exists(fitsDir):
        os.makedirs(fitsDir)
    outFilename = inFilename.format(UTCCurrentTime.year,
                                    UTCCurrentTime.month,
                                    UTCCurrentTime.day,
                                    int(counter),
                                    insMode)
    hdu.header['ORIGFILE'] = outFilename
    outFilename = fitsDir + outFilename
    print ("Creating empty FITS file in {} ...".format(outFilename))

    # Populate DATE keyword: UTC date and time the file was written
    # YYYY-MM-DDThh:mm:ss.sss
    hdu.header['DATE'] = hdu.header['DATE'].format(UTCCurrentTime.year,
                                                   UTCCurrentTime.month,
                                                   UTCCurrentTime.day,
                                                   UTCCurrentTime.hour,
                                                   UTCCurrentTime.minute,
                                                   UTCCurrentTime.second+UTCCurrentTime.microsecond*10**(-6))
    hdu.writeto(outFilename)
    with open(dataDir+"running_index.txt", "w") as f:
        f.write(str(int(counter)+1))
        print ("Created empty FITS file in {}".format(outFilename))
    status = 0
except IOError as e:
    print ("ERROR")
    status = 1
    raise e

status = 0
# __dict__["outFilename"] = outFilename
# __dict__["status"] = status
