import requests, time, json, os.path, base64, pprint

# from Crypto.Cipher import AES
# 
# msg_text = 'test some plain text here'.rjust(32)
# secret_key = '1234567890123456' # create new & store somewhere safe
# 
# 
# def encriptar(msg_text, secret_key):
#     return base64.b64encode(msg_text)
#     # cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
#     # encoded = base64.b64encode(cipher.encrypt(msg_text))
#     # return encoded
# 
# def descriptar(msg_text, secret_key):
#     return base64.b64decode(msg_text)
#     # cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
#     # decoded = cipher.decrypt(base64.b64decode(msg_text))
#     # return decoded.strip()









key = False
# # TODO: Desligar debug
# debug_curl = False 
debug_curl = True
keyPath = './token/token.key'

def login(auth, repetir:bool=True):
    print(auth)
    url = 'http://localhost:3000/integracao/pedido/authentication/'
    body = '{ "user": "'+auth['user']+\
            '", "lkgp": "'+auth['lkgp']+'"}'+\
            '", "apiname": "'+auth['apiname']+'"}'
    json = {
                "user"      : "SAC"
            ,   "lkgp"      : auth['lkgp']
            ,   "banco"     : auth['banco']
            ,   "apiname"   : auth['apiname']
        }
    
    
    
    headers = {"Content-Type": "application/json", "Accept": "application/json"}
    req = requests.request( 'POST', url, headers=headers, json=json ) 
    curlDebug(req)
    
    if req.status_code == 200:
        return req.text.replace('"', '')
    elif repetir:
        time.sleep(5)
        return login(auth, repetir=False)
    else:
        raise ValueError('Erro no Login')
        
    
    
def get_key(auth, force:bool=False):
    global key
    global keyPath
    
    existsKey = os.path.isfile(keyPath)
    
    if force:
        key = login(auth)
        
    elif key == False and existsKey:
        # TODO: Descriptografar key
        # Pensei em usar uma criptografia no arquivo, mas tive problemas
        # tentei usar "from Crypto.Cipher import AES" mas nao achoou AES
        with open(keyPath, 'r') as file:
            key = file.read()
        
    elif not existsKey:
        key = login(auth)
    
    else:
        key = key
        
    # TODO: Criptografar key
    """ with open(keyPath, 'w+') as file:
        file.write(key) """
        
    return key 
    
    
def envio_pedido(auth, pedido, repetir:bool=False, debug=False):
    global debug_curl
    debug_curl = debug
    url = 'http://localhost:3000/integracao/pedido/pedido/'
    body = json.dumps(pedido)
    headers = {
        "Content-Type": "application/json", 
        "Accept": "application/json",
        "x-access-token": get_key(auth)
    }
    req = requests.request( 'POST', url, headers=headers, data=body ) 
    curlDebug(req)
    
    # se nao estiver autorizado, pega um novo token e reenvia
    if req.status_code == 401 or req.status_code == 400:
        headers["x-access-token"] = get_key(auth, force=True)
        req = requests.request( 'POST', url, headers=headers, data=body ) 
        curlDebug(req)
    
    return req
    
    
def curlDebug(req):
    global debug_curl
    if debug_curl:
        pprint.pprint(req.request.url)
        print("##~~##~~##~~##~~##~~##~~##~~##~~##~~##~~##~~")
        print("-----------------status_code-----------------")
        pprint.pprint(req.status_code)
        print("---------------------------------------------")
        print("")
        print("")
        print("-------------------headers-------------------")
        pprint.pprint(req.headers)
        print("---------------------------------------------")
        print("")
        print("")
        print("-------------------content-------------------")
        #pprint.pprint(req.content)
        print("---------------------------------------------")
        print("")
        print("")
        print("##~~##~~##~~##~~##~~##~~##~~##~~##~~##~~##~~")
    
    
def get_cliente(auth, cnpj):
    
    if not cnpj :
        return ''
    
    consulta = {"VLCPFCNPJ": cnpj,}
    url = 'http://localhost:3000/integracao/pedido/tabela/TBCLIENTE/'
    
    body = json.dumps(consulta)
    #pprint.pprint(body)
    headers = {
        "Content-Type": "application/json", 
        "Accept": "application/json",
        "x-access-token": get_key(auth)
    }
    req = requests.request( 'POST', url, headers=headers, data=body ) 
    #curlDebug(req)
    
    
    
    pprint.pprint(req.content)
    
    rJson = req.json()
    
    return rJson[0]['CDCLIENTE'] if len(rJson) else ' '
    
    
    
if __name__ == "__main__":
    
    
    auth = {
        "empresa" :    "1" , 
        "filial"  :    "1" , 
        "user"    :  "RICARDOMI" , 
        "passw"    : "1234" , 
        "lkgp"    :  "latinex" , 
        "banco"   :  "latinex" , 
    }
    cd = get_cliente(auth, "45543915007518")
    # cd = get_cliente(auth, "XXXXXXXXXXXXXX")
    
    #print(cd)
    exit()
    
    
    print(auth["user"])
    envio_pedido(auth=auth, pedido={})
    