# $Header: https://oberon.oapd.inaf.it/shins/trunk/shins/src/scripts/templates/SHINS_SW_TEST/shinsapp.py 3745 2021-10-04 15:28:40Z depa $
import sys
import Ice
import traceback
import sharknir
from util import variables as uvars
from util import exception
from util.shinsLogger import logger

class SHINSApp(object):
    '''class handling the connection to the ZeroCIce proxy. Used by all of
    the template scripts, which on their side overloads the run method.'''
    def __init__(self, id=""):
        self._status = uvars.EXIT_SUCCESS
        self._ic = None
        self._obsController = None
#        self._sensController = None
        self._id = id

    def run(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None, **kwargs):
        '''overloaded by templates scripts'''
        pass

    def main(self, ins_s=None, det_s=None, tel_s=None, rtc_s=None,
             seqProxyAsString  = "ObsControlAdapterSeq:default -p 10500",
#             sensProxyAsString = "ObsControlAdapterSen:default -p 10500",
             sysProxyAsString  = "ObsControlAdapterSys:default -p 10500", **kwargs):
        '''method handling the connection to Ice proxy and launching the
        run method'''
        logger.info("ShinsApp main Started")
        try:
            self._ic = Ice.initialize(sys.argv)
            seqBase  = self._ic.stringToProxy(seqProxyAsString)
#            sensBase = self._ic.stringToProxy(sensProxyAsString)
            sysBase = self._ic.stringToProxy(sysProxyAsString)
            self._obsController  = sharknir.obsControl.SequencerPrx.checkedCast(seqBase)
#            self._sensController = sharknir.obsControl.SensorsPrx.checkedCast(sensBase)
            self._sysController = sharknir.obsControl.SystemPrx.checkedCast(sysBase)
            if (not self._obsController): # or (not self._sensController)):
                raise RuntimeError("Invalid proxy")

            status = self.run(ins_s, det_s, tel_s, rtc_s, **kwargs)
#            logger.debug("self.run returned : {}".format(status)) 
            self._status = status[0] if type(status) == tuple else status

        except KeyboardInterrupt as e:
            logger.error("KeyboardInterrupt")
            self._status = uvars.EXIT_FAILURE
            logger.debug(self._status)
            # kwargs["EXIT"] = True
            # sys.exit()
        except Exception as e:
            logger.error("Exception: %s - %s" % (e.message, str(e.args)))
            logger.error(e)
            self._status = uvars.EXIT_FAILURE 
            logger.debug(self._status)
            # kwargs["EXIT"] = True
        finally:
            # executed weather an exception is raised or not
            if self._ic:
            # Clean up
                try:
                    self._ic.destroy()
                except:
                    #traceback.print_exc()
                    self._status = uvars.EXIT_FAILURE
                    logger.debug(self._status)

            # is EXIT excplicit? if not the default behaviour is to exit
            # if ("EXIT" in kwargs):
            #     print (kwargs["EXIT"])
            #     if (kwargs["EXIT"] == True):
            #         sys.exit(self._status)
            # else:
            #     sys.exit(self._status)

        if(self._status == uvars.EXIT_SUCCESS):
            logger.info("ShinsApp  main successfully completed")
        else:
            logger.info("ShinsApp main completed with errors")
        return self._status

    @property
    def obsController(self):
        return self._obsController

#    @property
#    def sensController(self):
#        return self._sensController

    @property
    def sysController(self):
        return self._sysController

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, value):
        if value > 0:
            self._status = uvars.EXIT_FAILURE # failure
        if value <= 0:
            self._status = uvars.EXIT_SUCCESS # success

    @property
    def id(self):
        return self._id

    @id.setter
    def id(self, value):
        self._id = value
