
#!/usr/bin/python
# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/SHINS_SW_TEST/SHINS_TEST_INTERDICTION.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_INTERDICTION.py /opt/tan/lib/python/site-packages/shins/templates/SHINS_SW_TEST

class SHINS_TEST_INTERDICTION_App(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 
        '''
        #logger.info(__name__)

        self.status = uvars.EXIT_SUCCESS
        lsFitsFilename = []
        units_s = {};
        ErrorCounter = 0
        det_s = {}
        try:
            obsController = self.obsController

            #####################
            # TEST INTERDICTION #
            #####################
            det_s.clear()
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "SHINS_TEST_INTERDICTION"})
            logger.info("################################################")
            logger.info("########### SHINS_TEST_INTERDICTION ############")
            logger.info("################################################")

            logger.info("Starting Test TEST_CORO_WHEEL_INTERDICTION")

            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Interdiction Condition"})

            det_s.clear()
            det_s["CAL_FIBER_DEP"] = "DEFOCUS_IN"
            logger.info("Moving Fiber Deployer to DEFOCUS_IN")
            async = obsController.begin_setupInstrument(det_s)
            self.status = obsController.end_setupInstrument(async)
            if(self.status == uvars.EXIT_FAILURE):
                logger.error("Error moving fiber in defocus")
            ufun.error_handler(self.status, "setupInstrument")

            ##########################
            # setupInstrument START  #
            ##########################

            det_s["FTEST"] = "3"
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Attempt Named Moving CORO Wheel"})
            
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            logger.debug("Enumerating instrument setup")
            for element, value in det_s.items():
                logger.debug("Element : % 15s  -  Value % 15s    " % (element, value))
            
            logger.info("Moving Coro Wheel to named position SLIT1")
            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

            #########################################
            # setupInstrumentAbsolutePosition START #
            #########################################
            logger.info("Starting setupInstrumentAbsolutePosition")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Absolute Moving CORO Wheel and CAL Fiber"})
            
            det_s.clear()
            det_s["CORO_SLIT_W"] = 1378900.
            det_s["CAL_FIBER_DEP"] = -1650000.
            units_s["CORO_SLIT_W"] = "STEPS"
            units_s["CAL_FIBER_DEP"] = "STEPS"
            logger.info("Moving Coro Wheel to absolute position %d" % det_s["CORO_SLIT_W"])
            logger.info("Moving Fiber Deployer to absolute position %d" % det_s["CAL_FIBER_DEP"])
            async = obsController.begin_setupInstrumentAbsolutePosition(det_s, units_s)
            logger.info("Ending Move to Absolute Position")
            self.status = obsController.end_setupInstrumentAbsolutePosition(async)
            if(self.status == uvars.EXIT_FAILURE):
                logger.error("Error Setting up Instrument to absolute position")
                ErrorCounter += 1

            #########################################
            # setupInstrumentRelativePosition START #
            #########################################
            logger.info("Starting setupInstrumentRelativePosition")
            det_s.clear()
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Relative Moving CORO Wheels and CAL Fiber"})
            
            det_s.clear()
            det_s["CORO_SLIT_W"] = 500.
            det_s["CAL_FIBER_DEP"] = -500.
            units_s["CORO_SLIT_W"] = "STEPS"
            units_s["CAL_FIBER_DEP"] = "STEPS"
            logger.info("Moving Coro Wheel with relative step of %d" % det_s["CORO_SLIT_W"])
            logger.info("Moving Fiber Deployer with relative step of %d" % det_s["CAL_FIBER_DEP"])
            async = obsController.begin_setupInstrumentRelativePosition(det_s, units_s)
            self.status = obsController.end_setupInstrumentRelativePosition(async)
            if(self.status == uvars.EXIT_FAILURE):
                logger.error("Error Setting up Instrument to relative Position")
                ErrorCounter += 1
            
            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_INTERDICTION(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_INTERDICTION: begin')
    
    app = SHINS_TEST_INTERDICTION_App()
    if not (uvars.filenameSHINS in kwargs.keys()):
        kwargs[uvars.filenameSHINS] = SHINS_TEST_INTERDICTION.__name__
    status = app.main(ins_s, det_s, tel_s, rtc_s, **kwargs)

    logger.info('SHINS_TEST_INTERDICTION: end')
    return status


if __name__ == "__main__":
    SHINS_TEST_INTERDICTION(ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs)

