#!python

from dockclean import containers as docker_containers
from dockclean import images as docker_images
import click
import logging

logging.basicConfig(format="%(message)s")
LOG = logging.getLogger()


@click.group("docker_clean_tool")
def cli():
    """
    This tool provides commands to remove unwanted docker images and containers
    """


@click.command()
@click.option(
    "--remove_all",
    "-a",
    help="Removes all containers. Only stopped containers are removed by default.",
    is_flag=True,
    flag_value=True,
    show_default=True,
)
@click.option("--verbose", "-v", help="Give more output", is_flag=True, flag_value=True)
def containers(remove_all, verbose):
    """
    Removes unwanted containers.
    """
    if verbose:
        LOG.setLevel(logging.INFO)
    if remove_all:
        docker_containers.remove_all_containers(LOG)
    else:
        docker_containers.remove_all_stopped_containers(LOG)


@click.command()
@click.option(
    "--pattern", "-p", help="Removes all images matching the given regex pattern"
)
@click.option(
    "--repository", "-r", help="Removes all images belonging to the given repository"
)
@click.option(
    "--exclude",
    "-e",
    help="Excludes images matching the given regex pattern from being removed",
)
@click.option("--verbose", "-v", help="Show output", is_flag=True, flag_value=True)
def images(pattern, repository, exclude, verbose):
    """
    Removes unwanted images. Only dangling images are removed by default.
    """
    if verbose:
        LOG.setLevel(logging.INFO)
    docker_images.remove_all_dangling(LOG)
    if pattern:
        docker_images.remove_with_pattern(pattern, exclude, LOG)
    if repository:
        docker_images.remove_all_from_repository(repository, exclude, LOG)


cli.add_command(containers)
cli.add_command(images)

if __name__ == "__main__":
    cli()
