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

__all__ = ["logger"]

# Cell

from typing import *

# Internal Cell

import os
import typer
from typer import echo
from tabulate import tabulate
import pandas as pd

from ..client import Client
from . import helper
from ..logger import get_logger, set_level

# Internal Cell

app = typer.Typer(
    help="""Set of commands for managing the API keys in 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 airt token command 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.

        You can now set the API key in the environment variable AIRT_SERVICE_TOKEN and start accessing airt services with it.""",
)

# Cell

logger = get_logger(__name__)

# Internal Cell


@app.command()
@helper.requires_auth_token
def create(
    name: str = typer.Option(..., "--name", "-n", help="Name for the new API key"),
    expiry: int = typer.Option(
        ...,
        "--expiry",
        "-e",
        help="The validity for the newly created API key in the number of days",
    ),
    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 API key in airt service"""

    from ..client import APIKey

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

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


# Internal Cell


@app.command()
@helper.requires_auth_token
def ls(
    offset: int = typer.Option(
        0,
        "--offset",
        "-o",
        help="The number of records to offset at the beginning of the API keys list. If None, then the default value 0 will be used.",
    ),
    limit: int = typer.Option(
        100,
        "--limit",
        "-l",
        help="The maximum number of records 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 API keys will also be included in the result.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output only ids of API keys separated by space",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """List available API keys."""

    from ..client import APIKey

    df = APIKey.ls(offset=offset, limit=limit, include_disabled=include_disabled)

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

    if quiet:
        ids = df["id"].astype(str).to_list()
        typer.echo("\n".join(ids))
    else:
        typer.echo(tabulate(df, headers="keys", tablefmt="plain", showindex=False))


# Internal Cell


@app.command()
@helper.requires_auth_token
def details(
    id: int = typer.Argument(
        ...,
        help="The API Key ID in the airt service.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Return details of the given API Key."""

    from ..client import APIKey

    df = APIKey.details(api_key_id=int(id))

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

    typer.echo(tabulate(df, headers="keys", tablefmt="plain", showindex=False))


# Internal Cell


@app.command()
@helper.requires_auth_token
def rm(
    id: int = typer.Argument(
        ...,
        help="The API Key ID in the airt service.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output the deleted API key id only.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Remove the API key from airt service."""

    from ..client import APIKey

    df = APIKey.delete(api_key_id=int(id))

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

    if quiet:
        typer.echo(df.iloc[0]["id"])
    else:
        typer.echo(tabulate(df, headers="keys", tablefmt="plain", showindex=False))
