import asyncio
import aiohttp

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from funciones.mainselenium import *


def abrir_navegador(headless=False):
    opciones = Options()

    opciones.headless = headless

    driver = webdriver.Firefox(firefox_profile=os.getenv("RUTA_PERFIL"),
                               options=opciones,
                               executable_path=os.getenv("RUTA_GECKO"))

    url_whatsapp = "https://web.whatsapp.com/"

    driver.get(url_whatsapp)

    print("dps de get")
    sesion_iniciada = True

    while sesion_iniciada is False:
        try:
            driver.find_element_by_css_selector(ids['verificar_sesion'])
            sesion_iniciada = True
            print("<<<Sesion iniciada>>>")
        except:
            print("no inicio sesion")
            continue
    return driver


async def iniciar(loop, *args):
    print(f"[[ Tareas a ejecutar: {len(args)} ]]")

    tareas = [coro[0](*coro[1]) for coro in args]

    try:
        await asyncio.gather(*tareas)

        loop.run_forever()
    except Exception as e:
        print("CERRANDING")
        loop.stop()


async def apagar(loop, driver):
    """Se encarga de frenar un loop que esta corriendo, finalizando correctamente todas las tareas."""

    driver.quit()

    tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]

    for _task in tasks:
        _task.cancel()

    await asyncio.gather(*tasks, return_exceptions=True)

    loop.stop()