#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import sys, re, gzip, base64, json.decoder
from collections import deque
from datetime import datetime


def oi():
    print("FOI !")

def unzip(zip):
    xml = str(gzip.decompress(base64.b64decode(zip)))
    retorno = findFirst(r'^b\'(.*)\'', xml)
    return retorno

def getXpath(xpath, xml):
    xpath = makeXpath (xpath)
    return findFirst(xpath, xml)

def findFirst(regex, text):
    encontrou = re.findall(regex, text)
    return encontrou[0] if len(encontrou) > 0 else " " 
    
def findAll(regex, text):
    encontrou = re.findall(regex, text)
    return encontrou if len(encontrou) > 0 else []
    
def makeXpath(xpath):
    xpath = xpath.replace('/@', '@')
    # ^(?:\s*<\?xml [^?>]*\?>)*\s*
    xpath = makeXpath_recursive( deque( xpath.split('/') ) )
    return xpath

def makeXpath_recursive(arrXpath):
    if len(arrXpath) > 1:
        tag = arrXpath.popleft()
        #          ,--------------------------------------------> Abertura da tag
        #          |    ,---------------------------------------> Seguido de qualquer coisa diferente do fechamento e e depois o fechamento
        #          |    |      ,--------------------------------> Seguido de qualquer coisa, literal ou nao, usado para pegar qualquer tag com qualquer valor, ateh ateh a que queremos
        #          |    |      |         ,----------------------> Tag interna pode ser essa regex atual repetida ou a regex que pega o valor desejado
        #          |    |      |         |         ,------------> Seguido de qualquer coisa, literal ou nao
        #          |    |      |         |         |       ,----> Fechamento da tag
        #         _|_  _|__  __|__  _____|______  _|__   __|____ 
        #        /   \/    \/     \/            \/     \/       \
        return "<{tag}[^>]*>[\w\W]*{trag_interna}[\w\W]*<\/{tag}>".format( 
            tag=tag, 
            trag_interna=makeXpath_recursive(arrXpath) 
        )
        
    else:
        # se for atributo
        if '@' in arrXpath[0]:
            tag, attr = arrXpath[0].split('@')
            #         ,--------------------------------------> Tag que iremos buscar o atributo
            #         |     ,--------------------------------> Qualquer coisa diferente da tag de abertura, usado para pegar todos os atributos ateh achar o que queremos
            #         |     |      ,-------------------------> Atrubuto desejado no formato atributo="valor"
            #         |     |      |      ,------------------> Valor do atributo, eh o grupo capiturado
            #         |     |      |      |           ,------> Qualquer coisa ath fechar a tag
            #         |     |      |      |           |    ,-> Todo o conteudo da tag
            #        _|__  _|_  ___|__  __|_______  __|_  _|_ 
            #       /    \/   \/      \/          \/    \/   \
            return "<{tag}[^<]*{attr}\=\"([^\"]*)\"[^>]*>[^<]*".format(
                tag=tag,
                attr=attr
            )
            
            
        # se nao for atributo
        else:
            #             ,.------------------------> Abertura da tag buscada
            #             |        ,.---------------> Grupo capiturado do valor da tag, pega tudo ateh a tag de abertura
            #             |        |         ,.-----> Fechamento da tag buscada
            #        _____|____  __|__  _____|______ 
            #       /          \/     \/            \
            return "<{tag}[^>]*>([^<]*)<\/{tag}[^>]*>".format(
                tag=arrXpath[0]
            )
        
    












