import sys
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from datetime import datetime
from selenium.webdriver.support.expected_conditions import (
    new_window_is_opened
)
from pathlib import Path
from datetime import timedelta  


def menu_156(browser, descricao, filtro, pasta):
    time.sleep(2)
    erro = WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.ID, "errormsglabel")))
    erroConteudo = erro.text
    print(erroConteudo)
    if (erroConteudo.find("enviada") > -1):
        continuar = WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.ID, "-1")))
        continuar.click()
        time.sleep(2)
        
        browser.switch_to.window(browser.window_handles[-1] )
        
        parar = False
        tentativas = 1
        qtdeTentativas = 6
        sequencia = ""
        while tentativas <= qtdeTentativas:
            atualiza = WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.ID, "1"))) 
            atualiza.click()
            time.sleep(2)
            browser.switch_to.window(browser.window_handles[-1] )
            tabela = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, "tblsr")) )
            linhas = tabela.find_elements(By.TAG_NAME, "tr")
            for linha in  linhas:
                colunas = linha.find_elements(By.TAG_NAME, "td")
                if (colunas[5].text != "Fone"):
                    if (colunas[1].text == descricao) and (colunas[3].text.upper() == 'BI'):
                        if colunas[8].text == 'Baixar':
                            sequencia = colunas[0].text
                            baixar = colunas[8].find_elements(By.TAG_NAME, "a")
                            baixar[0].click()
                            time.sleep(5)
                            parar = True
                        break
            tentativas = tentativas + 1
            if parar:
                break
            time.sleep(10)
    
    time.sleep(15)
    data_criacao = lambda f: f.stat().st_ctime
    data_modificacao = lambda f: f.stat().st_mtime
    
    directory = Path(pasta)
    #files = directory.glob('CSV*.sswweb')
    files = directory.glob(filtro)
    sorted_files = sorted(files, key=data_modificacao, reverse=True)
    relatorioArquivo = ""
    for f in sorted_files:
        relatorioArquivo = f
        break
    print(relatorioArquivo)
    return relatorioArquivo
#FIM FUNC menu_156    
