from datetime import datetime
import constant
import classes.Color

color = classes.Color.Color()
class DebugSys:
    remote_addr = 0
    debug_on = False

    """
        Tag Name - Utilizado para destacar o debug
    """
    tagName = 'NONE'

    """
        Content Indentation - Habilite para visualizar content json com indentação
    """
    useIndent = True

    """Ultimo Write()"""
    txtLastWrited = False
    
    def __init__(self):
        self.setDebugOn(constant.OPERATION_IN_DEBUG)
        ###self.setDebugOn(False)

    def setTag(self,name):
        self.tagName = name

    def writeAlert(self,*text):
        if self.debug_on:
            _txt = ''
            for t in text:
                _txt += ' %s' % t

            modeOperation = 'DEV' if constant.OPERATION_IN_DEV else 'PRD'
            dateTimeStamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            _tag = '' if self.tagName is False else '[%s]' % self.tagName
            self.txtLastWrited = '\033[96m[%s %s %s] \033[93m%s %sALERT %s%s\033[0m' % (modeOperation,self.remote_addr or 'XXX.YY.ZZ.00',dateTimeStamp,_tag,color.RED,color.YELLOW,_txt)

            print(self.txtLastWrited)

    def writeErr(self,errCode,*text):
        _txt = f'Ex{errCode:03}'
        self.write('%s %s' % (_txt,text) )

    def write(self,*text):
        if self.debug_on:
            _txt = ''
            for t in text:
                _txt += ' %s' % t

            modeOperation = 'DEV' if constant.OPERATION_IN_DEV else 'PRD'
            dateTimeStamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            _tag = '' if self.tagName is False else '[%s]' % self.tagName
            self.txtLastWrited = '\033[96m[%s %s %s] \033[93m%s\033[0m%s' % (modeOperation,self.remote_addr or 'XXX.YY.ZZ.00',dateTimeStamp,_tag,_txt)

            print(self.txtLastWrited)

    def setDebugOn(self,value):
        self.debug_on = value
    
    def setRemoteAddr(self,remote_addr):
        """Set remote_addr"""
        self.remote_addr = remote_addr

    def var_export(self, obj, ret_val = False) :
        import os,sys,pprint
        if ret_val == False :
            pprint.pprint(obj)
            return None
        fn = '/path/to/temp/file'
        temp = sys.stdout             # store original stdout object for later
        sys.stdout = open(fn, 'w')    # redirect all prints to temp file
        pprint.pprint(obj)
        sys.stdout.close()
        sys.stdout = temp             # restore print commands to interactive prompt
        return open(fn, 'r').read()
