# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/SHINS_SW_TEST/SHINS_TEST_CLASH_MANAGEMENT_ABS.py 3724 2021-10-14 14:26:48Z laud $
# -*- coding: utf-8 -*-

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_ABS.py /opt/tan/lib/python/site-packages/shins/templates/SHINS_SW_TEST

class SHINS_TEST_CLASH_MANAGEMENT_ABS_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
        TEST = 1
        if(kwargs):
            TEST = eval(kwargs["test_s"])
            logger.info("TEST = %d" % TEST)
        try:
            obsController = self.obsController
            if TEST == 1:
                TEST += 1
                ############################################################
                ################## Clash Management Test ###################
                ############################################################
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "Starting Clash Management Abs Test"})
                logger.info("##########################################")
                logger.info("######## Clash Management Abs 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"] = "-1545000" # "FOCUS_IN"
                det_s["APODIZER_W"] = "A#1307205.00" # "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")

            if TEST == 2:
                TEST += 1
                #################### Coro Wheel to SLIT1 ###################
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "CORO Wheel to SLIT1"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "553820.00" #"SLIT1"
                logger.info("Moving CORO_SLIT_W to 553820.00 (SLIT1)")
                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, CAL_FIBER in safe pos ###
                logger.info("############################################################")
                logger.info("### TEST 2: CORO not changing pos, CAL_FIBER in safe pos ###")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 2: CORO not changing pos, CAL_FIBER in safe pos"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "553820.00" #"SLIT1"
                det_s["APODIZER_W"] = "A#1049344.00" # "HOLE4"
                det_s["CAL_FIBER_DEP"] = "A#380000.00" # "NO_FIBERS"
                logger.info("Moving CAL_FIBER_DEP to %s" % det_s["CAL_FIBER_DEP"])
                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 2")
                ufun.error_handler(self.status, "setupInstrument")

            if TEST == 3:
                TEST += 1
                ######## 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["CAL_FIBER_DEP"] = "DEFOCUS_IN"
                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 Restoring CAL_FIBER_DEP dangerous position")
                ufun.error_handler(self.status, "setupInstrument")

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

            if TEST == 4:
                TEST += 1
                ####### TEST 4: CAL fiber in safe position not moving ######
                logger.info("############################################################")
                logger.info("####### TEST 4: CAL fiber in safe position not moving ######")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 4: CAL fiber in safe position not moving"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "1850000.00" #HOLE
                det_s["APODIZER_W"] = "791883.00" #"HOLE3"
                logger.info("Moving CORO_SLIT_W to 1850000.00")
                logger.info("Moving APODIZER_W to 791883.00")
                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")

            if TEST == 5:
                TEST += 1
                ########## TEST 5: CAL FIBER Safe moving to Safe ###########
                logger.info("############################################################")
                logger.info("########## TEST 5: CAL FIBER Safe moving to Safe ###########")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 5 CAL FIBER Safe moving to Safe"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "A#553820.00" #"SLIT1"
                det_s["APODIZER_W"] = "A#1049344.00" # "HOLE4"
                det_s["CAL_FIBER_DEP"] = "-1545000.00" # "FOCUS_IN"
                logger.info("Moving CORO_SLIT_W to A#553820.00")
                logger.info("Moving APODIZER_W to A#1049344.00 (HOLE4)")
                logger.info("Moving CAL_FIBER_DEP to -1545000.00 (FOCUS_IN)")
                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")

            if TEST == 6:
                TEST += 1
                ######## TEST 6: CAL FIBER Moving to dangerous pos #########
                logger.info("############################################################")
                logger.info("######## TEST 6: CAL FIBER Moving to dangerous pos #########")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 6: CAL FIBER Moving to dangerous pos"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "1850000.00" #HOLE
                det_s["APODIZER_W"] = "1307205.00" # "HOLE5"
                det_s["CAL_FIBER_DEP"] = "-2700000.00" # "DANGER_IN"
                logger.info("Moving CORO_SLIT_W to 1850000.00")
                logger.info("Moving APODIZER_W to 1307205.00")
                logger.info("Moving CAL_FIBER_DEP to -2700000.00")
                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")

            if TEST == 7:
                TEST += 1
                ########## TEST 7: CAL FIBER is in dangerous pos ###########
                logger.info("############################################################")
                logger.info("########## TEST 7: CAL FIBER is in dangerous pos ###########")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 7: CAL FIBER is in dangerous pos"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "553820.00" #"SLIT1"
                det_s["APODIZER_W"] = "1049344.00" # "HOLE4"
                logger.info("Moving CORO_SLIT_W to 553820.00")
                logger.info("Moving APODIZER_W to 1049344.00")
                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")

            if TEST == 8:
                TEST += 1
                # TEST 8: CAL FIBER is in dangerous pos moving to safe  pos#
                logger.info("############################################################")
                logger.info("# TEST 8: CAL FIBER is in dangerous pos moving to safe  pos#")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 8: CAL FIBER is in dangerous pos moving to safe  pos"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "A*335.4346" # "A\"1207564.56"# "A$5.854436" # "A#1850000.00" #HOLE
                det_s["APODIZER_W"] = "A*237.017" # "1307205.00" # "HOLE5"
                det_s["CAL_FIBER_DEP"] = "A%-10609.515" # "-1545000.00" # "FOCUS_IN"
                logger.info("Moving CORO_SLIT_W to 335.4346° (A#1850000.00)")
                logger.info("Moving APODIZER_W to 237.017° (1307205.00)")
                logger.info("Moving CAL_FIBER_DEP to -10609.515 µm (-1545000) steps")
                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 8")
                ufun.error_handler(self.status, "setupInstrument")

            if TEST == 9:
                TEST += 1
                ######## 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"] = "A*335.4346" # "A\"1207564.56"# "A$5.854436" # "A#1850000.00" #HOLE
                det_s["APODIZER_W"] = "A*237.017" # "1307205.00" # "HOLE5"
                det_s["CAL_FIBER_DEP"] = "DEFOCUS_IN"
                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 Restoring CAL_FIBER_DEP dangerous position")
                ufun.error_handler(self.status, "setupInstrument")

                ### TEST 9: CAL FIBER is in dang. pos moving to dang. pos ##
                logger.info("############################################################")
                logger.info("### TEST 9: CAL FIBER is in dang. pos moving to dang. pos ##")
                logger.info("############################################################")
                obsController.sashaGetIndiMsges({"FTEST" : "3", "SEPARATOR" : "TEST 9: CAL FIBER is in dang. pos moving to dang. pos"})
                det_s.clear()
                det_s["CORO_SLIT_W"] = "A#553820.00" # "SLIT1"
                det_s["APODIZER_W"] = "A#1049344.00" # "HOLE4"
                det_s["CAL_FIBER_DEP"] = "A%-18540.9" # "-2700000.00" # "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 9")
                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_ABS(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_ABS: begin')
    
    app = SHINS_TEST_CLASH_MANAGEMENT_ABS_App()
    if not (uvars.filenameSHINS in kwargs.keys()):
        kwargs[uvars.filenameSHINS] = SHINS_TEST_CLASH_MANAGEMENT_ABS.__name__
    status = app.main(ins_s, det_s, tel_s, rtc_s, **kwargs)

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


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