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

from SHARKNIR_gen_base import SHARKNIR_gen_base

class SHARKNIR_gen_tiptilt_dark_multi_freq(SHINSApp):

    @exception.handler_for_run
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''Close tiptilt loop
        '''

        logger.info(__name__)
        logger.info('Taking dark for TT at multiple frequencies ... ')

        self.status = uvars.EXIT_SUCCESS
        obsController = self.obsController

        self.gen_base = SHARKNIR_gen_base();        gen_base = self.gen_base
        
        #bprint("CRED Temp : {} deg C".format(rtc_s["TTTEMPCRED"]))
        if self.paragraph("SET CRED TEMPERATURE"):
            logger.info("Setting temperature to {}...".format(rtc_s["TTTEMPCRED"]))
            temp = float(ufun.get_status_by_name(os=obsController, names=["rtc_cred_temp"])[0])
            temp_f = float(rtc_s["TTTEMPCRED"])
            thrs = 0.5
            TO_time = (5)*60 # minutes
            timedOut = False
            temp_reached = abs(temp_f - temp) <= thrs
            start = time.time()
            
            while(not temp_reached and not timedOut):
                obsController.RTCTTSendCameraCommand("set temperatures sensor {}".format(rtc_s["TTTEMPCRED"]))
                logger.debug("Wait ...")
                time.sleep(10)
                self.status, res = obsController.RTCTTSendCameraCommand("temperatures")
                print(res)
                temp = float(ufun.get_status_by_name(os=obsController, names=["rtc_cred_temp"])[0])
                temp_reached = abs(temp_f - temp) <= thrs
                logger.debug("Latest temperature read : {}. Desired temperature reached? {} ".format(temp, temp_reached))
                end = time.time()
                print(end-start)
                if (end-start > TO_time):
                    timedOut = True
                    logger.error("Timed Out while waiting desired temperature...")
                    self.abort()
                
            logger.info("Setting temperature to {}... DONE".format(rtc_s["TTTEMPCRED"]))
        
        frequencies = [50, 100, 250, 500, 1000]

        ###########################################
        # START AND WAIT INSTRUMENT AND RTC SETUP #
        ###########################################

        if self.paragraph("Prepare Instrument and RTC setup"):
            logger.info("Waiting ins setup ...")
            self.status, _, __ = gen_base.main(ins_s, **kwargs)
            logger.info("Waiting ins setup ... DONE")

            # logger.info("Waiting RTC setup ...")
            # self.status = obsController.RTCTTExecuteSetup(rtc_s)
            # logger.info("Waiting RTC setup ... DONE")

            
        ##########################################
        # Take an image on RTC at each frequency #
        ##########################################
        
        if self.paragraph("Taking RTC images"):

            for freq in frequencies:
                # dark_rtc_s = {
                #     "TTTESTTIME"  : rtc_s["TTTESTTIME"],
                #     "TTFRAMERATE" : str(freq)
                # }
                
                freq_s = {"TTFRAMERATE" : str(freq)}
                rtc_s.update(freq_s)
                print(rtc_s)
                logger.info("Save and update RTC dark at {} Hz".format(freq))
                # logger.info("TT update dark")
                self.status, self.filenames = obsController.RTCTTTeccamExpose(rtc_s)
                ufun.error_handler(self.status, "RTCTTTeccamExpose")
                logger.info("TT update dark... DONE. fits cube is {}".format(self.filenames))
                time.sleep(5)
                
