# coding: utf-8
"""sdc2-score-admin.

A command line interface administrator client for the SKA Science Data
Challenge scoring service.

Usage:
    sdc2-score-admin group ls [-u] [--raw]
    sdc2-score-admin group add GROUP_NAME...
    sdc2-score-admin group rm GROUP_ID...
    sdc2-score-admin user ls [--raw]
    sdc2-score-admin user add FIRST_NAME LAST_NAME USERNAME EMAIL GROUP [PASSWORD]
    sdc2-score-admin user rm USER_ID...
    sdc2-score-admin submission ls [-n LIMIT] [-c VERSION] [--raw]
    sdc2-score-admin submission rm SUBMISSION_ID [-c VERSION]
    sdc2-score-admin (-h | --help | --version)

Options:
    -u                   Show users in the group.
    --raw                Display unformatted API response JSON object.
    -n LIMIT             Maximum number of submissions to show [default: 20].
    -c VERSION           Catalogue version (1.full, 1.dev) [default: 1.full].
    -h, --help           Show this screen.
    --version            Show the version.

Arguments:
    EMAIL                Email address of the user.
    FIRST_NAME           User's first name.
    GROUP_ID             Group name or ID, minimally matched.
    GROUP_NAME           Name of the group.
    LAST_NAME            User's last name.
    PASSWORD             Password for the user. Optional, autogenerated if not set.
    SUBMISSION_ID        UUID for a submission, minimally matched
    USER_ID              User name or ID, minimally matched.
    USERNAME             User's user name

"""
import logging

from docopt import docopt

from ska_sdc2_scoring_utils import admin_api
from ska_sdc2_scoring_utils.logs import init_logger
from ska_sdc2_scoring_utils.api_common import LOG
from ska_sdc2_scoring_utils.__version__ import __version__


def process_commands(args):
    """Process commands.

    Args:
        args(dict): Dictionary of command line arguments.

    """
    # Group commands
    if args["group"]:
        # List groups
        if args["ls"]:
            admin_api.group_list(show_users=args["-u"], output_raw=args["--raw"])
        # Add a group
        if args["add"]:
            admin_api.group_add(args["GROUP_NAME"])
        # Remove a group
        if args["rm"]:
            admin_api.group_delete(args["GROUP_ID"])

    # User commands:
    if args["user"]:
        # List users
        if args["ls"]:
            admin_api.user_list(output_raw=args["--raw"])
        # Add a user
        if args["add"]:
            admin_api.user_add(
                first_name=args["FIRST_NAME"],
                last_name=args["LAST_NAME"],
                username=args["USERNAME"],
                email=args["EMAIL"],
                group_identifier=args["GROUP"],
                password=args["PASSWORD"],
            )
        # Remove a user
        if args["rm"]:
            admin_api.user_delete(args["USER_ID"])

    if args["submission"]:
        if args["ls"]:
            admin_api.submission_list(
                limit=int(args.get("-n")),
                catalogue_version=args["-c"],
                output_raw=args["--raw"],
            )

        if args["rm"]:
            admin_api.submission_rm(
                identifier=args["SUBMISSION_ID"], catalogue_version=args["-c"]
            )


def main():
    """Script main."""
    args = docopt(__doc__, version=__version__)

    verbosity = args.get("-v", 0)
    init_logger(
        logging.DEBUG if verbosity > 0 else logging.INFO,
        verbosity > 0,
        verbosity == 2,
    )

    try:
        process_commands(args)
    except (ValueError, RuntimeError) as error:
        LOG.error("ERROR: %s", error)


if __name__ == "__main__":
    main()
