from datetime import datetime, timezone, timedelta

from generic.gn_json import gn_json

class gn_files(gn_json):

    def __tratar_valor(self, valor, **kwargs):
        tipo        = kwargs.get('tipo')
        variacao    = kwargs.get('variacao')
        try:
            if len(valor) > 0 :
                if   "INT" in tipo  :
                    valor = int(valor) 
                elif "DOUBLE" in tipo :
                    valor = float(valor) 
                elif  "DECIMAL" in tipo  :
                    #valor = valor.replace(".","").replace(",",".")
                    valor = float(valor)
                elif "DATETIMEF" in tipo :
                    valor = "{0}-{1}-{2}T{3}:{4}:{5}.000Z".format(valor[0:4],valor[4:6],valor[6:8],valor[8:10],valor[10:12],valor[12:14]) if int(valor) else None
                elif "DATETIME" in tipo :
                    valor = "{0}-{1}-{2} {3}:{4}:{5}".format(valor[0:4],valor[4:6],valor[6:8],valor[8:10],valor[10:12],valor[12:14]) if int(valor) else None
                elif "DATE" in tipo :
                    valor = "{0}-{1}-{2}".format(valor[0:4],valor[4:6],valor[6:8]) if int(valor) else None
                elif "I" in variacao :
                    valor = self.__img_encode64(valor)
                else :
                    valor = valor.strip()
                    valor = valor.replace("§","\n")
        except:
            valor = ""
            
        if not valor and tipo in  ['INT', 'DOUBLE', 'DATETIME', 'DATE', 'DATETIMEF'] :
            valor = None
        return valor
    
    def txt_to_dict(self):
        files           = self.rote_data.get('files')
        entrada         = files.get('entrada' )
        
        txt             = self.readFile(entrada)
        linhas_arquivo  = txt.split("\n")
        cabecalho       = linhas_arquivo[0]
        corpo           = linhas_arquivo[1:]
        
        estrutura = {}
        
        mapa_operacoes = {}
        
        
        propriedades_coluna = cabecalho.split(";")
        for propriedade in propriedades_coluna:
            estrutura_nome, estrutura_tipo, estrutura_tamanho, estrutura_variacao, estrutura_is_not_null = propriedade.split("|")
            if estrutura_nome == 'FGCUD':
                continue
                
            
            estrutura[estrutura_nome] = ({
                "tipo":estrutura_tipo,
                "tamanho":estrutura_tamanho,
                "variacao":estrutura_variacao,
                "not_nulo":estrutura_is_not_null == 'S',
            })
            
        
        def_ = ""
        for linha in corpo:
            
            linha_dados = linha.split(";")
            mapa_estrutura = {}
            for index, valor in enumerate(linha_dados):
                hed_ = propriedades_coluna[index]
                if(index == 0 ):
                    def_ = valor
                    if(def_ not in mapa_operacoes):
                        mapa_operacoes[def_] = []
                    continue
                    
                estrutura_nome = hed_.split("|")[0]
                
                estrutura_atual = estrutura[estrutura_nome]
                
                mapa_estrutura[estrutura_nome] = ({
                    **estrutura_atual,
                    "valor": self.__tratar_valor(valor, **estrutura_atual)
                })
                #linha_dados_json.append(mapa_estrutura)
            mapa_operacoes[def_].append(mapa_estrutura)
                
        return mapa_operacoes