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

from SHARKNIR_gen_base import SHARKNIR_gen_base

class SHARKNIR_cal_SkyBackground(SHINSApp):
    
    @exception.handler_for_run
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
       
        self.status = uvars.EXIT_SUCCESS
        obsController = self.obsController
        self.status = uvars.EXIT_SUCCESS

        self.gen_base = SHARKNIR_gen_base();        gen_base = self.gen_base
        ################################
        # TRANSFORM COORDINATES TO RAD #
        ################################

        logger.debug("Enumerating telescope setup")
        for element, value in tel_s.items():
            logger.debug("Element : % 15s  -  Value % 15s    " % (element, value))

        tel_s = ufun.to_radians(tel_s)

        logger.debug("Enumerating telescope setup after conversion")
        for element, value in tel_s.items():
            logger.debug("Element : % 15s  -  Value % 15s    " % (element, value))
        
        #########################
        # SEND TELESCOPE OFFSET #
        #########################
        if self.paragraph("SEND TELESCOPE OFFSET"): 
            
            logger.info("Start Offset ...")
            self.status = obsController.OffsetPointing(tel_s)
            logger.info("Start Offset ... DONE")

        #################
        # SETUP + IMAGE #
        #################
            
        gen_base.main(ins_s, det_s)

        ##############################
        # SEND TELESCOPE OFFSET BACK #
        ##############################
        if self.paragraph("SEND TELESCOPE OFFSET BACK"): 

            offsetx = str(-float(tel_s["OFFSETX"]))
            offsety = str(-float(tel_s["OFFSETY"]))
            
            tel_s.update({"OFFSETX": offsetx,       # in radians
                          "OFFSETY": offsety,       # in radians
                          })
            
            logger.info("Start Offset ...")
            self.status = obsController.OffsetPointing(tel_s)
            logger.info("Start Offset ... DONE")
