from typing import List
from uuid import UUID

import click
from tabulate import tabulate

from sym.flow.cli.helpers.api import SymAPI
from sym.flow.cli.helpers.global_options import GlobalOptions
from sym.flow.cli.helpers.utils import human_friendly, utc_to_local
from sym.flow.cli.models import User


@click.command(name="list", short_help="List all Sym Tokens")
@click.make_pass_decorator(GlobalOptions, ensure=True)
def tokens_list(options: GlobalOptions) -> None:
    """
    Lists all Sym Tokens in your Organization generated by `symflow tokens issue`
    """
    table_data = get_tokens_data(options.sym_api)
    click.echo(tabulate(table_data, headers="firstrow"))


def get_tokens_data(api: SymAPI) -> List[List[str]]:
    tokens = api.get_tokens()

    user_cache = {}
    table_data = [["Token ID", "User", "Created By", "Expires At", "Last Used", "Label"]]
    for t in tokens:
        user = get_user(t.user.id, user_cache, api)
        created_by = get_user(t.created_by.id, user_cache, api)
        table_data.append(
            [
                t.identifier,
                user.sym_identifier,
                created_by.sym_identifier,
                human_friendly(utc_to_local(t.expires_at)),
                human_friendly(utc_to_local(t.updated_at)),
                t.label,
            ]
        )

    return table_data


def get_user(user_id: UUID, user_cache: dict, api: SymAPI) -> User:
    if user := user_cache.get(user_id):
        return user
    else:
        user = user_cache[user_id] = api.get_user_by_id(user_id)

    return user
