# 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
from ..env import SERVICE_TOKEN, CLI_CMD

# Internal Cell

app = typer.Typer(
    help=f"""A set of commands for managing the API keys in the server.

        Both the API key and the token can be used for accessing the {CLI_CMD} 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. 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
        commands available in the **{CLI_CMD} api-key** to list, revoke the keys at any time.

        Once the new API key is generated, you can set it in the **{SERVICE_TOKEN}** environment variable and
        start accessing the 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="API key name."),
    expiry: int = typer.Option(
        ...,
        "--expiry",
        "-e",
        help="The validity for the 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."""

    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 API keys 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 API keys 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 API key ids separated by space",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Return the list of API keys available in the server."""

    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="API key id.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Return details of an API key."""

    from ..client import APIKey

    df = APIKey.details(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="API key id.",
    ),
    quiet: bool = typer.Option(
        False,
        "--quiet",
        "-q",
        help="Output only the deleted API key id.",
    ),
    debug: bool = typer.Option(
        False,
        "--debug",
        "-d",
        help="Set logger level to DEBUG and output everything.",
    ),
) -> None:
    """Delete an API key from the server."""

    from ..client import APIKey

    df = APIKey.delete(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))
