# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/SHINS_SW_TEST/SHINS_TEST_CLASH_MANAGEMENT.py 3724 2021-10-14 14:26: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_CLASH_MANAGEMENT.py /opt/tan/lib/python/site-packages/shins/templates/SHINS_SW_TEST

class SHINS_TEST_CLASH_MANAGEMENT_App(SHINSApp):
    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''template for log INDI messages
        '''
        #logger.info(__name__)

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

            ############################################################
            ################## Clash Management Test ###################
            ############################################################
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Starting Clash Management Test"})
            logger.info("############################################################")
            logger.info("################### Clash Management Test ##################")
            logger.info("############################################################")

            ################ Cal Fiber to Safe position ################
            ############## TEST 1: CORO Wheel not involved #############
            logger.info("############################################################")
            logger.info("############## TEST 1: CORO Wheel not involved #############")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 1: CORO Wheel not involved"})
            det_s.clear()
            det_s["CAL_FIBER_DEP"] = "FOCUS_IN"
            det_s["APODIZER_W"] = "HOLE5"
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 moving fiber in defocus")
            ufun.error_handler(self.status, "setupInstrument")

            #################### Coro Wheel to SLIT1 ###################
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "CORO Wheel to SLIT1"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            logger.info("Moving COR_FILT_W to %s" % det_s["CORO_SLIT_W"])
            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 moving CRO to SLIT1")
            ufun.error_handler(self.status, "setupInstrument")

            ############### TEST 2: CORO not changing pos ##############
            logger.info("############################################################")
            logger.info("############### TEST 2: CORO not changing pos ##############")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 2: CORO not changing pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["APODIZER_W"] = "HOLE"
            det_s["CAL_FIBER_DEP"] = "NO_FIBERS"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 2")
            ufun.error_handler(self.status, "setupInstrument")

            #################### Coro Wheel to SLIT1 ###################
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "CORO Wheel to SLIT1"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["CAL_FIBER_DEP"] = "DEFOCUS_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 moving CRO to SLIT1")
            ufun.error_handler(self.status, "setupInstrument")

            ############### TEST 2 BIS: CORO not changing pos ##############
            logger.info("############################################################")
            logger.info("############# TEST 2 BIS: CORO not changing pos ############")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 2 BIS: CORO not changing pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["APODIZER_W"] = "HOLE"
            det_s["CAL_FIBER_DEP"] = "NO_FIBERS"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 2")
            ufun.error_handler(self.status, "setupInstrument")

            #################### Coro Wheel to HOLE ####################
            ####### TEST 3: CAL fiber in safe position not moving ######
            logger.info("############################################################")
            logger.info("####### TEST 3: CAL fiber in safe position not moving ######")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 3: CAL fiber in safe position not moving"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "HOLE"
            det_s["APODIZER_W"] = "HOLE3"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            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 moving CORO Wheel to HOLE")
            ufun.error_handler(self.status, "setupInstrument")

            ########## TEST 4: CAL FIBER Safe moving to Safe ###########
            logger.info("############################################################")
            logger.info("########## TEST 4: CAL FIBER Safe moving to Safe ###########")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 4 CAL FIBER Safe moving to Safe"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["APODIZER_W"] = "HOLE4"
            det_s["CAL_FIBER_DEP"] = "FOCUS_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 4")
            ufun.error_handler(self.status, "setupInstrument")

            ######## TEST 5: CAL FIBER Moving to dangerous pos #########
            logger.info("############################################################")
            logger.info("######## TEST 5: CAL FIBER Moving to dangerous pos #########")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 5: CAL FIBER Moving to dangerous pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "HOLE"
            det_s["APODIZER_W"] = "HOLE5"
            det_s["CAL_FIBER_DEP"] = "DEFOCUS_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 5")
            ufun.error_handler(self.status, "setupInstrument")

            ########## TEST 6: CAL FIBER is in dangerous pos ###########
            logger.info("############################################################")
            logger.info("########## TEST 6: CAL FIBER is in dangerous pos ###########")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 6: CAL FIBER is in dangerous pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["APODIZER_W"] = "HOLE4"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            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 in TEST 6")
            ufun.error_handler(self.status, "setupInstrument")

            # TEST 7: CAL FIBER is in dangerous pos moving to safe  pos#
            logger.info("############################################################")
            logger.info("# TEST 7: CAL FIBER is in dangerous pos moving to safe  pos#")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 7: CAL FIBER is in dangerous pos moving to safe  pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "HOLE"
            det_s["APODIZER_W"] = "HOLE5"
            det_s["CAL_FIBER_DEP"] = "FOCUS_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 7")
            ufun.error_handler(self.status, "setupInstrument")

            ######## Restoring CAL_FIBER_DEP Dangerous Position ########
            logger.info("######## Restoring CAL_FIBER_DEP Dangerous Position ########")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "######## Restoring CAL_FIBER_DEP Dangerous Position ########"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "HOLE"
            det_s["APODIZER_W"] = "HOLE5"
            det_s["CAL_FIBER_DEP"] = "DEFOCUS_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 7")
            ufun.error_handler(self.status, "setupInstrument")

            ### TEST 8: CAL FIBER is in dang. pos moving to dang. pos ##
            logger.info("############################################################")
            logger.info("### TEST 8: CAL FIBER is in dang. pos moving to dang. pos ##")
            logger.info("############################################################")
            obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 8: CAL FIBER is in dang. pos moving to dang. pos"})
            det_s.clear()
            det_s["CORO_SLIT_W"] = "SLIT1"
            det_s["APODIZER_W"] = "HOLE"
            det_s["CAL_FIBER_DEP"] = "DANGER_IN"
            logger.info("Moving CORO_SLIT_W to %s" % det_s["CORO_SLIT_W"])
            logger.info("Moving APODIZER_W to %s" % det_s["APODIZER_W"])
            logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
            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 in TEST 6")
            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_CLASH_MANAGEMENT(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_CLASH_MANAGEMENT: begin')
    
    app = SHINS_TEST_CLASH_MANAGEMENT_App()
    if not (uvars.filenameSHINS in kwargs.keys()):
        kwargs[uvars.filenameSHINS] = SHINS_TEST_CLASH_MANAGEMENT.__name__
    status = app.main(ins_s, det_s, tel_s, rtc_s, **kwargs)

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


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