# 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 airt service.

    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 successfully authenticated, you can create any number of API keys and set an expiration date for each key individually. Also, you can use the other
    methods available in the APIKey class to list, revoke the keys at any time.
    """

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

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

        Returns:
            The access token and the type of the token as a dictionary.

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

        A simple 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 _get_columns() -> list:
        """Returns the list of columns to be added to the DataFrame."""

        return ["id", "name", "created", "expiry", "disabled"]

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

        Args:
            offset: The number of rows to offset at the beginning of the API keys
                list from the server.If **None**, then the default value **0** will be used.
            limit: The maximum number of rows 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 with the list of available API keys.

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

        An example to list the available datasources:

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

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

        columns = APIKey._get_columns()

        return generate_df(lists, columns)

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

        Args:
            api_key_id: The id of the API key in the airt service.

        Returns:
            A pandas dataframe with the details of the API key.

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

        An example to get details of an API key (id=1) from airt service:

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

        details = Client.get_data(relative_url=f"/apikey/{api_key_id}")

        columns = APIKey._get_columns()

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

    @staticmethod
    def delete(api_key_id: int) -> pd.DataFrame:
        """Delete an API key from airt service

        Args:
            api_key_id:  The id of the API key in the airt service.

        Returns:
            A pandas dataframe with the details of the deleted API key.

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

        An example to delete an API key (id=1) from airt service:

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

        response = Client.delete_data(relative_url=f"/apikey/{api_key_id}")

        columns = APIKey._get_columns()

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