#! /usr/bin/env python3

import astropy.io.fits as fits
import sys
sys.path.append('./data/scripts/python_wrapper/sixtesoft/')
import sixte


sixte.check_pythonversion(3, 6)

def check_att_fov(fout, expos):
    # check if the criterion: 50% margin on FoV is fulfilled
    prec = 0.01  # be careful, we've only got low number statistics

    hdul = fits.open(fout)
    data = hdul[1].data
    time_range = max(data['time']) - min(data['time'])
    ## as the FoV is 1deg and the speed is 1deg/ksec, we expect
    ## 1ksec duration, making it 1.5ksec with margins
    margin_dur = 1.5e3;

    if abs(margin_dur - time_range)/margin_dur > prec:
        print(" *** Error expected photon interval {:.3f}, but found  {:.3f}".format(margin_dur, time_range))
        return 1
    else:
        return 0


# TEST OPTIONS
exposure = 4e3



defpath = sixte.defpath(testname = "phogen_e2e")
print(f'   *** testing {defpath.testname}  *** ')

ret_val = sixte.phogen(defpath.testname_pholist,
                       defpath.xml,
                       defpath.simput,
                       logfile=defpath.log,
                       prefix='',
                       test=True)

sixte.check_returncode(ret_val, defpath.fullname)

sixte.check_fdiff(defpath.ref_path + defpath.refname_pholist,
                  defpath.testname_pholist,
                  defpath.fullname)


defpath = sixte.defpath(testname = "phogen_e2e", subtestname='Attitude_FoV-Margin')
print(f'   *** testing {defpath.testname}  *** ')

ret_val = sixte.phogen(defpath.testname_pholist,
                       defpath.xml,
                       defpath.simput,
                       expos=exposure,
                       attitude=defpath.attitude,
                       prefix='',
                       logfile=defpath.log,
                       test=True)

ret_val = check_att_fov(defpath.testname_pholist, exposure)

sixte.check_returnvalue(ret_val, defpath.fullname)


# clean output
sixte.clean_output()
