import time
from datetime import datetime

import os
import random
from time import sleep

from decouple import config
from selenium import webdriver
from selenium.common.exceptions import (
    NoSuchElementException,
    ElementNotVisibleException,
    ElementNotSelectableException,
    ElementNotInteractableException
)
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as CondicaoExperada
from selenium.webdriver.support.ui import WebDriverWait

# from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

url = "https://login.vivo.com.br/loginmarca/" \
      "appmanager/marca/publico?origem=https://login.vivo.com.br/saml2/idp/sso/login-return#"


class VivoWithSelenium:
    def __init__(self):
        if os.name != "posix":  # Windows
            self.driver = webdriver.Chrome()
            # self.driver = webdriver.Firefox()
            # QDO FOR ATUALIZAR O NAVEGADOR
            # self.driver = webdriver.Chrome(ChromeDriverManager().install())
            chrome_options = webdriver.ChromeOptions()
            # chrome_options.add_argument('--headless')
        else:
            CHROMEDRIVER_PATH = "/usr/local/bin/chromedriver"
            WINDOW_SIZE = "1920,1080"
            chrome_options = Options()
            # chrome_options.add_argument("--headless")
            chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
            chrome_options.add_argument("--no-sandbox")
            self.driver = webdriver.Chrome(
                executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options
            )
        self.wait = WebDriverWait(
            self.driver,
            10,
            poll_frequency=1,
            ignored_exceptions=[
                NoSuchElementException,
                ElementNotVisibleException,
                ElementNotSelectableException,
            ],
        )

    @staticmethod
    def type_like_a_person(sentence, single_input_field):
        """ Essa função basicamente simulará a digitação de uma pessoa"""
        print("going to start typing message into message share text area")
        for letter in sentence:
            single_input_field.send_keys(letter)
            sleep(random.randint(1, 10) / 30)

    def percorrer_tabela(self, pagina, first_page_previous, _f):
        driver = self.driver
        quantidade_linha_tabela = len(driver.find_elements_by_xpath("//tbody//tr"))
        first_page_current = driver.find_elements_by_xpath("//tbody//tr")[0].text
        print(
            f"Primeira Página Anterior..: {first_page_previous}\n"
            f"Primeira Página Atual..: {first_page_current}\n"
            f"Página..: {pagina} "
            f"- Quantidade de linhas...: {quantidade_linha_tabela}"
        )
        pagina += 1
        if first_page_current not in first_page_previous:
            for row in driver.find_elements_by_xpath("//tbody//tr"):
                _f.write(row.text)
                # print(row.text)
                _f.write("\n")
            print("*" * 60)
            return pagina, quantidade_linha_tabela, first_page_current
        first_page_current = False
        return pagina, quantidade_linha_tabela, first_page_current

    def main(self, url, params):
        fileout = f"vivo3g-{datetime.today().date()}-" \
                  f"{datetime.today().time().isoformat().split('.')[0].replace(':', '_')}.txt"
        if os.name != "posix":  # Windows
            homepath = os.path.expanduser(os.getenv("USERPROFILE"))
            desktoppath = "Desktop"
            archive = os.path.join(homepath, desktoppath, fileout)
        else:
            os.chdir("../")
            homepath = os.getcwd()
            archive = os.path.join(homepath, fileout)
        driver = self.driver
        driver.get(url)
        xpath_clicar_button_login = '//*[@id="main-menu"]/div[1]/nav/div/a[3]'
        clicar_button_login = self.wait.until(
            CondicaoExperada.element_to_be_clickable(
                (By.XPATH, xpath_clicar_button_login)
            )
        )
        clicar_button_login.click()
        sleep(random.randint(5, 7) / 30)
        # xpath_vivo_login_username = '//input[@name="vivo_login_username"]'
        # self.driver.find_element_by_xpath(xpath_vivo_login_username).send_keys(params["cpf"])
        xpath_vivo_login_username = '/html/body/div[2]/div[2]/header/div/div/div/div[1]/div[1]/div[2]/div/div/div[2]' \
                                    '/form/div[1]/div/div/div[1]/label/div/input'
        input_email = self.wait.until(
            CondicaoExperada.element_to_be_clickable(
                (By.XPATH, xpath_vivo_login_username)
            )
        )
        input_email.clear()
        self.type_like_a_person(params["cpf"], input_email)
        sleep(random.randint(5, 7) / 30)
        # xpath_input_password = '//input[@name="vivo_login_password"]'
        xpath_input_password = '/html/body/div[2]/div[2]/header/div/div/div/div[1]/div[1]/div[2]/div/div/div[2]/form' \
                               '/div[2]/div/div/div[1]/label/div/input'
        input_password = self.wait.until(
            CondicaoExperada.element_to_be_clickable(
                (By.XPATH, xpath_input_password)
            )
        )
        sleep(random.randint(5, 7) / 30)
        input_password.clear()
        self.type_like_a_person(params["password"], input_password)
        sleep(random.randint(15, 18) / 30)
        xpath_button_login = "/html/body/div[2]/div[2]/header/div/div/div" \
                             "/div/div[1]/div[2]/div/div/div[2]/form/button"
        button_login = self.wait.until(
            CondicaoExperada.element_to_be_clickable((By.XPATH, xpath_button_login))
        )
        button_login.click()
        sleep(15)
        close_banner = driver.find_element_by_class_name("fecharAlert")
        try:
            close_banner.click()
        except ElementNotInteractableException:
            print("Sem banner para fechar")
        # Até aqui conecta no site
        sleep(5)
        url_extrato_detalhado = "https://meuvivo.vivo.com.br/content/vivo/meu-vivo/meu-consumo/consumo.html"
        driver.get(url_extrato_detalhado)
        sleep(5)
        consumido = driver.find_element_by_xpath(
            '//span[@data-bind="text:tabledata.Consumption"]'
        ).text
        consumido_em_porcentagem = driver.find_element_by_xpath(
            '//span[@data-bind="text:tabledata.ConsumptionPercent"]'
        ).text
        disponivel = driver.find_element_by_xpath(
            '//span[@data-bind="text:tabledata.available"]'
        ).text
        disponivel_em_porcentagem = driver.find_element_by_xpath(
            '//span[@data-bind="text:tabledata.availablePercent"]'
        ).text

        sleep(5)
        link_extrato_mais_detalhado = driver.find_element_by_xpath(
            '//a[@data-content-id="impl_see_detailed_extract_data"]'
        )
        try:
            link_extrato_mais_detalhado.click()
            sleep(5)
            pagina = 1
            first_page_previous = ""
            # print("Inicio da tabela")
            with open(archive, "w") as _f:
                _f.write(f"Consumido..: {consumido} em %..: {consumido_em_porcentagem}\n")
                _f.write(
                    f"Disponível..: {disponivel} em %..: {disponivel_em_porcentagem}\n"
                )
                _f.write(f'{"*" * 80}\n')
                (
                    pagina,
                    quantidade_linha_tabela,
                    first_page_previous,
                ) = self.percorrer_tabela(pagina, first_page_previous, _f)
                sleep(5)
                while True:
                    driver.find_element_by_xpath('//a[@title="Próxima página"]').click()
                    sleep(2)
                    (
                        pagina,
                        quantidade_linha_tabela,
                        first_page_previous,
                    ) = self.percorrer_tabela(pagina, first_page_previous, _f)
                    if quantidade_linha_tabela < 5 or not first_page_previous:
                        break
        except Exception:
            pass
        driver.close()


def load_txt():
    # fileout = "gasto_3g.txt"
    # name_initial = 'vivo'
    # extension = 'txt'

    homepath = os.path.expanduser(os.getenv("USERPROFILE"))
    desktoppath = "Desktop"
    path_to_desktop = os.path.join(homepath, desktoppath)
    os.chdir(path_to_desktop)

    list_arqs_txt = [f for f in os.listdir('.') if '.txt' in f and f.startswith('vivo')]

    archive = list_arqs_txt[-1]
    print("Abrindo arquivo...")
    with open(archive, "r") as _f:
        file_read = _f.readlines()
    formato = '%d/%m/%y'
    guardar_data = ''
    total_gasto = 0.0
    total_gasto_geral = 0.0
    for row in file_read[3:]:
        data = row.split(' ')[2]
        if not guardar_data:
            guardar_data = time.mktime(datetime.strptime(data, formato).timetuple())
        else:
            data_atual = time.mktime(datetime.strptime(data, formato).timetuple())
            if not guardar_data == data_atual:
                total_gasto = round(total_gasto, 2)
                print(f"Gasto Diário..: {total_gasto}\n{'-' * 100}")
                total_gasto_geral += total_gasto
                total_gasto = 0.0
                guardar_data = data_atual
                # break
        print(row)
        gasto = float(row.split(' ')[0])
        if 'kb'.upper() in row.split(' ')[1]:
            gasto = gasto / 1024
        horario = row.split(' ')[4]
        print(gasto, horario)
        total_gasto += gasto
        sleep(1)
    print(total_gasto_geral)
    return


if __name__ == "__main__":
    url = "https://www.vivo.com.br/para-voce"
    params = {}
    params["cpf"] = config("VIVO_CPF")
    params["password"] = config("VIVO_PASSWORD")
    bd = VivoWithSelenium()
    bd.main(url, params)
    # load_txt()
