# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/jira/auth.ipynb.

# %% auto 0
__all__ = ['JiraAuth', 'JiraAuthPat']

# %% ../../nbs/jira/auth.ipynb 2
import urllib.parse as parse
from dataclasses import dataclass, field
import base64
import httpx

import domolibrary_extensions.client as gd

# %% ../../nbs/jira/auth.ipynb 4
@dataclass
class _JiraAuth_Required:
    instance: str  # 'your-domain.atlassian.net'


@dataclass
class _JiraAuth_Optional:
    base_url: str = None
    is_datacenter: bool = False

# %% ../../nbs/jira/auth.ipynb 5
@dataclass
class JiraAuth(_JiraAuth_Optional, _JiraAuth_Required, gd.Auth):
    pass

# %% ../../nbs/jira/auth.ipynb 6
@dataclass
class _JiraAuthPat_Required:
    email: str
    pat: str = field(repr=False)

    def __post_init__(self):
        self.pat = self.pat.strip()

# %% ../../nbs/jira/auth.ipynb 7
@dataclass
class JiraAuthPat(_JiraAuth_Optional, _JiraAuthPat_Required, _JiraAuth_Required):
    def __post_init__(self):
        if not self.instance.startswith("https://"):
            self.instance = f"https://{self.instance}"

        self.base_url = self.instance
        self.instance = parse.urlparse(self.instance).netloc
        print(self.instance)

    def generate_auth_header(self):
        if self.is_datacenter:
            return {"Authorization": f"Bearer {self.pat}"}

        auth_str = base64.b64encode(f"{self.email}:{self.pat}".encode("ascii")).decode(
            "ascii"
        )
        return {"Authorization": f"Basic {auth_str}"}

    async def who_am_i(self, client: httpx.AsyncClient = None, debug_api: bool = False):
        url = f"{self.base_url}/rest/api/2/myself"

        response = await gd.get_data(
            method="GET",
            url=url,
            auth=self,
            debug_api=debug_api,
            client=client,
        )
        return response
