from urllib.parse import quote as urlencode

import httpx

from pylibrus.api import base_get_rq
from pylibrus.exceptions import APIError


class Librus:
    def __init__(self, access_token: str):
        self.access_token = access_token
        self._client: httpx.AsyncClient | None = None

    async def __aenter__(self):
        self._client = httpx.AsyncClient(timeout=30.0)
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self._client:
            await self._client.aclose()

    async def getResource(self, name: str):
        res = await base_get_rq(
            "/2.0/{}".format(urlencode(name, safe="/?&")),
            access_token=self.access_token,
            client=self._client
        )
        if res.status_code != 200:
            raise APIError(f"Status code: {res.status_code}, Response: {res.json()}")
        return res.json()
