# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/tpl/testOB_tiptilt_get_cube.py 3724 2021-08-30 14:26:48Z depa $

import sys
from util.shinsLogger import logger
from shinsapp import SHINSApp
from util import variables as uvars
from util import functions as ufun
from util import exception

class testOB_tiptilt_get_cube(SHINSApp):

    @exception.handler_for_run
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''Check that BCU has been initialized, then send specific command
        to CRED2 camera
        '''

        logger.info(__name__)
        obsController = self.obsController
        self.status = uvars.EXIT_SUCCESS

        ########################
        # Take an image on RTC #
        ########################

        repetitions = int(rtc_s["REPEAT"])
        for repetition in range(1, repetitions+1):

            if self.paragraph("EXPOSING TECCAM"): 

                logger.info("Integration time is set to {} ms".format(float(rtc_s["TTTESTTIME"])/1e3))

                ###########################
                # CHECK IF LOOP IS CLOSED #
                ###########################
                
                dev_status = ufun.get_status_by_name(obsController, ["rtc_dm_loop","ND_FILT_W"])
                loop_status = dev_status[0]
                nd_filt     = dev_status[1]
                
                if loop_status == None:
                    logger.debug("loop_status is None, json read failed, read directly from RTCTT")
                    self.status, is_loop_closed = obsController.RTCTTRead(uvars.TTControlLoopEna, 1, "dsp")
                    loop_status = "CLOSED" if bool(is_loop_closed[0]) else "OPEN"

                
                logger.info("TT take image {}/{}".format(repetition, repetitions))
                self.status, rtc_fits_file = obsController.RTCTTTeccamExpose(rtc_s)
                ufun.error_handler(self.status, "RTCTTTeccamExpose")
                logger.info("TT take image: fits cube is {}".format(rtc_fits_file))
                logger.info("ND_FILT_W is in position {}".format(nd_filt))
                logger.info("Internal TT loop is {}".format(loop_status))
                #logger.info("Internal TT loop is {}".format(str("\033[1;32m "+loop_status+"\n")))
                
