import click
from tabulate import tabulate

from flask.cli import AppGroup

from pycs import app
from pycs.database.Project import Project
from pycs.util import FileOperations


project_cli = AppGroup("project", short_help="Project operations")

@project_cli.command()
@click.argument("project_id")
def generate_thumbnails(project_id):
    """ Generates thumbnails for a specific project or all project """

    if project_id == "all":
        projects = Project.query.all()
        app.logger.info(f"Generating thumbnails for all projects ({len(projects)})!")
    else:
        project = Project.query.get(project_id)
        if project is None:
            app.logger.error(f"Could not find project with ID {project_id}!")
            return
        app.logger.info(f"Generating thumbnails for project {project}!")
        projects = [project]

    for project in projects:
        FileOperations.generate_thumbnails(project)

@project_cli.command("list")
def list_projects():
    """ List information about existing projects """
    projects = Project.query.all()

    print(f"Got {len(projects)} projects")
    rows = [(p.id, p.name, p.description) for p in projects]

    print(tabulate(rows,
        headers=["id", "name", "description"],
        tablefmt="fancy_grid"
    ))
