# AUTOGENERATED! DO NOT EDIT! File to edit: ../../notebooks/CLI_Key.ipynb.

# %% auto 0
__all__ = ['logger']

# %% ../../notebooks/CLI_Key.ipynb 3
from typing import *

# %% ../../notebooks/CLI_Key.ipynb 4
import os
import typer
from typer import echo
from tabulate import tabulate
import pandas as pd

from airt.client import Client
from airt.cli import helper
from airt.logger import get_logger, set_level
from airt.constant import SERVICE_TOKEN, CLIENT_NAME

# %% ../../notebooks/CLI_Key.ipynb 7
app = typer.Typer(
    help=f"""A set of commands for managing the ApiKeys in the server.
        
        Both the ApiKey and the token can be used for accessing the {CLIENT_NAME} services. However, there is a 
        slight difference in generating and managing the two.
        
        For generating the ApiKey, you first need to get the developer token. Please refer to **{CLIENT_NAME} token** command documentation to generate one.
        
        After logging in with your developer token, you can create any number of new ApiKeys and can set an 
        expiration date individually. You can also access other commands available as part of **{CLIENT_NAME} api-key** sub-command to 
        list, revoke the ApiKeys at any time.

        Once the new API key is generated, please set it in the **{SERVICE_TOKEN}** environment variable to start accessing the {CLIENT_NAME} services with it.""",
)

# %% ../../notebooks/CLI_Key.ipynb 10
logger = get_logger(__name__)

# %% ../../notebooks/CLI_Key.ipynb 15
@app.command()
@helper.requires_totp()
@helper.requires_auth_token
def create(
    name: str = typer.Argument(..., help="The name of the ApiKey."),
    expiry: int = typer.Option(
        None,
        "--expiry",
        "-e",
        help="The validity of the API key in number of days. If not passed, then the default value None will be used to create an ApiKey with no expiry date!",
    ),
    otp: Optional[str] = typer.Option(
        None,
        "--otp",
        help="Dynamically generated six-digit verification code from the authenticator app. Please pass this optional argument only if the MFA is enabled for your account.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output access token only.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Create a new ApiKey

    !!! note

        - The name of the ApiKey must be unique. If not, an exception will be raised while creating a new key with an existing key's name.

        - The expiry for an ApiKey is optional. If not passed, then the default value None will be used to create an ApiKey with no expiry date!
    """

    from airt.client import APIKey

    response = APIKey.create(name=name, expiry=expiry, otp=otp)

    if quiet:
        typer.echo(response["access_token"])
    else:
        typer.echo(f"Access Token: {response['access_token']}")

# %% ../../notebooks/CLI_Key.ipynb 19
@app.command()
@helper.display_formated_table
@helper.requires_auth_token
def ls(
    user: Optional[str] = typer.Option(
        None,
        "--user",
        "-u",
        help=f"user_uuid/username associated with the ApiKey. To get the user account uuid/username, use the `{CLIENT_NAME} user details` command."
        f" If the user_uuid/username is not passed, then the currently logged-in user_uuid/username will be used.",
    ),
    offset: int = typer.Option(
        0,
        "--offset",
        "-o",
        help="The number of ApiKeys to offset at the beginning. If None, then the default value 0 will be used.",
    ),
    limit: int = typer.Option(
        100,
        "--limit",
        "-l",
        help="The maximum number of ApiKeys to return from the server. If None, then the default value 100 will be used.",
    ),
    include_disabled: bool = typer.Option(
        False,
        "--disabled",
        help="If set to **True**, then the disabled ApiKeys will also be included in the result.",
    ),
    format: Optional[str] = typer.Option(
        None,
        "--format",
        "-f",
        help="Format output and show only the given column(s) values.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output only ApiKey uuids.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> Dict["str", Union[pd.DataFrame, str]]:
    """Get the list of ApiKeys."""
    from airt.client import APIKey

    response = APIKey.ls(
        user=user, offset=offset, limit=limit, include_disabled=include_disabled
    )
    df = APIKey.as_df(response)

    df["created"] = helper.humanize_date(df["created"])
    df["expiry"] = helper.humanize_date(df["expiry"])

    return {"df": df}

# %% ../../notebooks/CLI_Key.ipynb 26
@app.command()
@helper.display_formated_table
@helper.requires_auth_token
def details(
    apikey: str = typer.Argument(
        ...,
        help="ApiKey uuid/name.",
    ),
    format: Optional[str] = typer.Option(
        None,
        "--format",
        "-f",
        help="Format output and show only the given column(s) values.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> Dict["str", Union[pd.DataFrame, str]]:
    """Get the details of an ApiKey."""

    from airt.client import APIKey

    df = APIKey.details(apikey=apikey)

    df["created"] = helper.humanize_date(df["created"])
    df["expiry"] = helper.humanize_date(df["expiry"])

    return {"df": df}

# %% ../../notebooks/CLI_Key.ipynb 29
@app.command()
@helper.display_formated_table
@helper.requires_totp()
@helper.requires_auth_token
def revoke(
    keys: List[str] = typer.Argument(
        ...,
        help="ApiKey uuid/name to revoke. To revoke multiple keys, please pass the uuids/names separated by space.",
    ),
    user: Optional[str] = typer.Option(
        None,
        "--user",
        help=f"user_uuid/username associated with the ApiKey. To get the user account uuid/username, use the `{CLIENT_NAME} user details` command."
        f" If the user_uuid/username is not passed, then the currently logged-in user_uuid/username will be used.",
    ),
    otp: Optional[str] = typer.Option(
        None,
        "--otp",
        help="Dynamically generated six-digit verification code from the authenticator app. Please pass this optional argument only if the MFA is enabled for your account.",
    ),
    format: Optional[str] = typer.Option(
        None,
        "--format",
        "-f",
        help="Format output and show only the given column(s) values.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output only the revoked ApiKey uuid(s).",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> Dict["str", Union[pd.DataFrame, str]]:
    """Revoke one or more ApiKeys"""

    from airt.client import APIKey

    keys = [key for key in keys]
    formated_keys = helper.separate_integers_and_strings(keys)

    df = APIKey.revoke(keys=formated_keys, user=user, otp=otp)  # type: ignore
    df["created"] = helper.humanize_date(df["created"])
    df["expiry"] = helper.humanize_date(df["expiry"])

    return {"df": df}
