import logging
from argparse import ArgumentParser, Namespace
from typing import Optional, List

from bagsy.bagsyhub import bagSyHub
from bagsy.database import Database
from bagsy.logger import setup_logging
from bagsy.parser import parse_and_exec

logger = logging.getLogger(__name__)


def setup_parser(parser: ArgumentParser) -> None:
    parser.add_argument("--list", action="store_true", help="List the connected accounts.")


def exec_cmd(db: Database, args: Namespace, _parser: ArgumentParser):
    if args.list:
        l = db.list_token()
        if l is None or len(l) == 0:
            logger.info("There is no bagSyHub token configured!")
            return None

        logger.info("Configured bagSyHub tokens are:")
        for login in l:
            logger.info(f"\t{login[0]}) {login[1]} ({login[2]})")
        return None

    instance_url = input("instance url (e.g. localhost:3000):")
    username = input("username:")
    token = input("token:")

    hub = bagSyHub(username, instance_url, token)
    data = hub.get("/auth/check")
    if data is None:
        return None
    logger.info(f"Hello {data['user']['firstname']} {data['user']['lastname']}!")
    db.save_token(instance_url, username, token)
    return None


def main(cli_args: Optional[List[str]] = None):
    setup_logging()

    parse_and_exec("bagsy.login",
                   "bag-login",
                   "A python cli tool to login to a bagSyHub instance.",
                   cli_args)


if __name__ == "__main__":
    main()
