
#!/usr/bin/python
# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/SHINS_SW_TEST/SHINS_TEST_INIT_MOTIONUNIT.py 3724 2021-10-13 17:43:48Z laud $

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
# import Basda
# import Ice
# import pyds9

# cp /home/shinsmgr/shins/src/scripts/templates/SHINS_SW_TEST/SHINS_TEST_INIT_MOTIONUNIT.py /opt/tan/lib/python/site-packages/shins/templates/SHINS_SW_TEST

#class SHINS_TEST_INIT_MOTIONUNIT_App(SHINSApp):
class SHINS_TEST_INIT_MOTIONUNIT(SHINSApp):

    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''Test Named Absolute and Relative movement of CORO Wheel in interdiction condition 
        '''
        self.status = uvars.EXIT_SUCCESS
        lsFitsFilename = []
        units_s = {};
        ErrorCounter = 0
        ins_s = {}
        det_s = {}
        det_s["APODIZER_W"] = "-10000."
        det_s["CORO_SLIT_W"] = "-10000."
        det_s["DB_FILT_W"] = "-10000."
        det_s["LYOT_GRISM_W"] = "-10000."
        det_s["ND_FILT_W"] = "-10000."
        det_s["DB_FILT_W"] = "-10000."
        det_s["SCI_FILT_W1"] = "-10000."
        det_s["SCI_FILT_W2"] = "-10000."

        det_s["INBEAM_DEP"] = "-10000."
        det_s["PUPIL_LENS_DEP"] = "-10000."
        det_s["SHUTTER"] = "-10000."

        det_s["INBEAM_TT_X"] = "-1000."
        det_s["INBEAM_TT_Y"] = "-1000."
        logger.debug("Enumerating instrument setup")
        for element, value in det_s.items():
            logger.debug("Element : % 15s  -  Value % 15s    " % (element, value))

        # # Il try/except viene gestito da un decoratore in SHINSApp.run()
        # try:
        obsController = self.obsController

        obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "SHINS_TEST_INIT_MOTIONUNIT"})
        logger.info("################################################")
        logger.info("########## SHINS_TEST_INIT_MOTIONUNIT ###########")
        logger.info("################################################")
        
        ###################
        # setupInstrument #
        ###################

        obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Setup Instrument"})
        
        logger.info("#################### setupInstrument ####################")
        var = input("Press 1 and Enter To Continue...")
        async = obsController.begin_setupInstrument(det_s)
        self.status = obsController.end_setupInstrument(async)
        if(self.status == uvars.EXIT_FAILURE):
            logger.error("Error Setting up Instrument")
            ErrorCounter += 1

        ####################
        # initCalibUnitAll #
        ####################

        logger.info("Starting Test TEST_CALIBUNIT_INITIALIZATION")

        logger.info("Starting home search for ALL calibration devices")
        var = input("Press 1 and Enter To Continue...")
        
        obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Motion Unit - All - Initialization"})

        async = obsController.begin_initMotionUnitAll()
        self.status = obsController.end_initCalibUnitAll(async)
        if(self.status == uvars.EXIT_FAILURE):
            logger.error("Error in initCalibUnitAll")
        ufun.error_handler(self.status, "setupInstrument")
        
        for element, value in det_s.items():
            ###################
            # setupInstrument #
            ###################

            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Setup Instrument"})
            ins_s.clear()
            ins_s[element] = "R#-10000."
            logger.info("#################### setupInstrument ####################")
            var = input("Press 1 and Enter To Continue...")
            async = obsController.begin_setupInstrument(ins_s)
            self.status = obsController.end_setupInstrument(async)
            if(self.status == uvars.EXIT_FAILURE):
                logger.error("Error Setting up Instrument")
                ErrorCounter += 1

            ####################
            # initMotionUnit #
            ####################

            logger.info("Starting Test TEST_MOTION_UNIT_INITIALIZATION")

            logger.info("Starting home search for ALL calibration devices")
            var = input("Press 1 and Enter To Continue...")
            
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Motion Unit - %s - Initialization" % element})

            async = obsController.begin_initMotionUnit([element])
            self.status = obsController.end_initMotionUnit(async)
            if(self.status == uvars.EXIT_FAILURE):
                logger.error("Error in initCalibUnitAll")
            ufun.error_handler(self.status, "setupInstrument")



        
        logger.info("Test TEST_CORO_WHEEL_INTERDICTION Completed detected %d/3 interdiction Conditions!" % ErrorCounter)
            
#         except Basda.ServiceException as e:
#             logger.error("Service Exception was thrown during insturment setup {}".format(e.errmsg))
#             self.status = uvars.EXIT_FAILURE
#         except exception.TemplateException as e:
#             logger.error(e)
#             raise e
#         except exception as e:
#             logger.error(e)
#             raise e
#         except StandardError as e:
#             logger.error(e)
#             raise e
            
#         return self.status



# def SHINS_TEST_INIT_MOTIONUNIT(ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
#     """
#     Test template, listening on Indi In channel

#     Parameters not used
#     ----------
#     ins_s : instument setup dictionary; keys are tags from OB file
#     det_s : detector setup dictionary; keys are tags from OB file
#     tel_s : telescope setup dictionary; keys are tags from OB file
#     rtc_s : real-time control system dictonary; keys are tags from OB file
#     **kwargs : optional dictionary with additional control keywords.
#                E.g. {"EXIT":False} is used to prevent template to call
#                sys.exit() method

#     Returns
#     -------
#     Integer value with status of operation:
#     0 for success
#     1 for failure
#     """

#     logger.info('SHINS_TEST_INIT_MOTIONUNIT: begin')
    
#     app = SHINS_TEST_INIT_MOTIONUNIT_App()
#     if not (uvars.filenameSHINS in kwargs.keys()):
#         kwargs[uvars.filenameSHINS] = SHINS_TEST_INIT_MOTIONUNIT.__name__
#     status = app.main(ins_s, det_s, tel_s, rtc_s, **kwargs)

#     logger.info('SHINS_TEST_INIT_MOTIONUNIT: end')
#     return status


if __name__ == "__main__":
    #SHINS_TEST_INIT_MOTIONUNIT(ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs)
    istanza = SHINS_TEST_INIT_MOTIONUNIT() 
    istanza.main(ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs)

