# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/API_Keys.ipynb (unless otherwise specified).

__all__ = ["APIKey"]

# Cell

from typing import *

# Internal Cell

import os

from datetime import datetime, timedelta, date

import pandas as pd
from fastcore.foundation import patch

from .client import Client
from ..logger import get_logger, set_level
from ..helper import get_data, post_data, delete_data, generate_df

# Internal Cell

logger = get_logger(__name__)

# Cell


class APIKey:
    """A class for managing the API keys in the server.

    Both the API key and the token can be used for accessing the airt services. However, there is a slight difference in generating and managing the two.

    For generating the API key, you first need to get the token. Please refer to the documentation of the `Client.get_token` method for generating one.

    Once the token is generated, you can create any number of API keys and set an expiration date individually. Also, you can use the other methods available
    in the APIKey class to list, revoke the keys at any time.
    """

    API_KEY_COLS = ["id", "name", "created", "expiry", "disabled"]

    @staticmethod
    def create(name: str, expiry: Union[int, timedelta, datetime]) -> Dict[str, str]:
        """Create a new API key.

        Args:
            name: API key name.
            expiry: The validity for the API key. This can be an integer representing the number of days till expiry, can be an
                instance of timedelta (timedelta(days=x)) or can be an instance of datetime.

        Returns:
            The API key and its type as a dictionary.

        Raises:
            ValueException: If the user is not authenticated.
            ConnectionError: If the server address is invalid or not reachable.

        An example to create a new API key with 1 year validity:

        ```python
        Client.get_token()

        APIKey.create(
            name="sample_key"
            expiry=365
        )
        ```
        """

        if isinstance(expiry, int):
            delta = datetime.now() + timedelta(days=expiry)
        elif isinstance(expiry, timedelta):
            delta = datetime.now() + expiry
        else:
            delta = expiry

        expiry_date = delta.strftime("%Y-%m-%dT%H:%M")

        return Client._post_data(
            relative_url="/apikey",
            data=dict(name=name, expiry=expiry_date),
        )

    @staticmethod
    def ls(
        offset: int = 0,
        limit: int = 100,
        include_disabled: bool = False,
    ) -> pd.DataFrame:
        """Return the list of API keys available in the server.

        Args:
            offset: The number of API keys to offset at the beginning. If None, then the default value 0 will be used.
            limit: The maximum number of API keys to return from the server. If None, then the default value 100 will be used.
            include_disabled: If set to **True**, then the disabled API keys will also be included in the result.

        Returns:
            A pandas Dataframe encapsulating the list of available API keys.

        Raises:
            ConnectionError: If the server address is invalid or not reachable.

        An example to list the available API keys:

        ```python
        APIKey.ls()
        ```
        """

        lists = Client._get_data(
            relative_url=f"/apikey/?include_disabled={include_disabled}&offset={offset}&limit={limit}"
        )

        return generate_df(lists, APIKey.API_KEY_COLS)

    @staticmethod
    def details(id: int) -> pd.DataFrame:
        """Return details of an API key.

        Args:
            id: API key id.

        Returns:
            A pandas Dataframe encapsulating the details of the API key.

        Raises:
            ValueException: If the id is invalid.
            ConnectionError: If the server address is invalid or not reachable.

        An example to get details of an API key:

        ```python
        APIKey.details(id=1)
        ```
        """

        details = Client._get_data(relative_url=f"/apikey/{id}")

        return pd.DataFrame(details, index=[0])[APIKey.API_KEY_COLS]

    @staticmethod
    def delete(id: int) -> pd.DataFrame:
        """Delete an API key from the server.

        Args:
            id: API key id.

        Returns:
             A pandas Dataframe encapsulating the details of the deleted API key.

        Raises:
            ValueException: If the id is invalid.
            ConnectionError: If the server address is invalid or not reachable.

        An example to delete an API key:

        ```python
        APIKey.delete(id=1)
        ```
        """

        response = Client._delete_data(relative_url=f"/apikey/{id}")

        return pd.DataFrame(response, index=[0])[APIKey.API_KEY_COLS]
