import aiohttp
import asyncio
import time
from traceback import TracebackException
from types import TracebackType

websites="""https://hbues.net
https://mail.hbues.net
https://uxmal.hbues.net
https://baizabal.xyz
https://bovedatecnologica.com
https://true-medic.com.mx"""


class AsyncRequest:
    def __init__(self) -> None:
        self._session = aiohttp.ClientSession()

    async def __aenter__(self) -> "AsyncRequest":
        return self

    async def __aexit__(
        self,
        exc_type: Exception,
        exc_val: TracebackException,
        traceback: TracebackType,
    ) -> None:
        await self.close()

    async def close(self) -> None:
        await self._session.close()



    async def make_http_get_request(self, url: str) -> str:
        async with self._session.request("GET", url) as response:
            response.raise_for_status()
            return await response.text()


    async def send_post(self):
         async with aiohttp.ClientSession() as session:

            url = 'http://localhost:8091'
            headers = {'gst-token': 'c656aba8-5c4b-43c1-a00e-45dbb0d3c14x'}

            payload = {'execute': 'true', 'user_agent': 'CustomBrowser/0.0.1'}

            async with session.post(url=f"{url}/stack",
                                    json=payload,headers=headers) as resp:
                print(await resp.text())

            url_get = f"{url}/events"
            headers_get = {'gst-token': 'c656aba8-5c4b-43c1-a00e-45dbb0d3c14b'}
            
            async with session.get(url_get,headers=headers_get) as resp:
                print(resp.status)
                print(await resp.text())


    async def get(self, url, session):
        try:                                                                                       
            async with session.get(url=url) as response:
                resp = await response.read()
                print("Successfully got url {} with resp of length {}.".format(url, len(resp)))
        except Exception as e:
            print("Unable to get url {} due to {}.".format(url, e.__class__))


    async def get_websites(self, urls):
        async with aiohttp.ClientSession() as session:
            ret = await asyncio.gather(*(self.get(url, session) for url in urls))
        print("Finalized all. Return is a list of len {} outputs.".format(len(ret)))




async def main() -> None:

    async with AsyncRequest() as my_request:
        html = await my_request.make_http_get_request("http://github.com/")
        post = await my_request.send_post()
        print(html)
        print(post)

        urls = websites.split("\n")

        start = time.time()
        req = await my_request.get_websites(urls)
        end = time.time()
        print("Took {} seconds to pull {} websites.".format(end - start, len(urls)))


if __name__ == "__main__":

    asyncio.run(main())

