
import Basda
from util import variables as uvars
from util.shinsLogger import logger
import Ice
import sys
import time
from Tkinter import TclError

class TemplateException(Exception):
    '''
    Custom exception for templates.
    '''
    def __init__(self, msg='Template Exception', *args, **kwargs):
        super(TemplateException, self).__init__(msg, *args, **kwargs)
        logger.warning(msg)
        
        return
    

def handler_for_run(run):
    '''
    Decorator for handling exceptions.
    Put it on top of the run() method
    in the shinsapp class.
    '''

    def inner_function(*args, **kwargs):

        this = args[0]  # It's the "self" of the class

        try:
            '''
            This is the content method in basetemplate
            which is implemented in each template.
            If all goes well, it is executed smoothly.
            '''
            run(*args, **kwargs)

        except TclError as e:
            logger.warning("Ignoring alignment algorithm display error : {}".format(e))
            pass

        # except Basda.ServiceException as e:
        #     logger.error("RUN: Insturment setup error {}".format(e.errmsg))
        #     self.status = uvars.EXIT_FAILURE

        #     this.todo = this.paragraph_number
        #     this.paragraph_number = 0
        #     this.paused = True

        # except TemplateException as e:
        #     logger.error("RUN: TemplateException: {}".format(e))

        #     # this.todo = this.paragraph_number
        #     # this.paragraph_number = 0
        #     # this.paused = True
        #     this.close_ice()
        #     sys.exit(1)

        # except StandardError as e:
        #     logger.error("RUN: StandardError. Cannot recover.")
        #     logger.error(e)
        #     this.close_ice()
        #     sys.exit(1)
            
        # except Ice.UnknownException as e:
        #     logger.error("RUN: Error from OS")
        #     logger.error(e)

        #     this.todo = this.paragraph_number
        #     this.paragraph_number = 0
        #     this.paused = True

        # except Ice.CommunicatorDestroyedException as e:
        #     logger.error("RUN: Error in destroying Ice communication")
        #     logger.error(e) 
        #     this.close_ice()
        #     sys.exit(1)

        # except SystemExit as e:
        #     logger.error("RUN: sys.exit() found. Closing Ice and exiting for real.")
        #     logger.error(e)
        #     this.close_ice()
        #     sys.exit(1)
            
        except Exception as e:
            logger.error("RUN: Exception: {}".format(type(e).__name__))
            logger.error(e)
            print(this.name)
            if this.name == "SHARKNIR_cal_tec_NCPA_trial":
                this.obsController.unsetFlags(8,0)
                logger.debug("Fits Fast Saving Mode DISABLED")

            #raise e

    return inner_function

