import click
import flask

from flask.cli import AppGroup

from pycs import app
from pycs.database.Project import Project

result_cli = AppGroup("result", short_help="Result operations")



@result_cli.command("export")
@click.argument("project_id")
@click.argument("indent", required=False)
@click.argument("output", required=False)
def export(project_id, output, indent):
    """ Export results for a specific project or for all projects """
    if project_id == "all":
        projects = Project.query.all()
        app.logger.info(f"Exporting results for all projects ({len(projects)})!")
        if output is None:
            output = "output.json"

    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"Exporting results for project {project}!")
        projects = [project]
        if output is None:
            output = f"output_project_{int(project_id):04d}.json"

    app.logger.info(f"Exporting to {output}")

    results = []

    for project in projects:
        project_files = [
            dict(**f.serialize(),
                results=[
                    dict(**r.serialize(), label=r.label.serialize() if r.label is not None else None)
                        for r in f.results.all()
                ])
                for f in project.files.all() if f.results.count() != 0
            ]

        results.append(dict(
            project_id=project.id,
            files=project_files,
            labels=[lab.serialize() for lab in project.labels.all()],
        ))


    if indent is not None:
        indent = int(indent)

    with open(output, "w", encoding="utf-8") as out_f:
        flask.json.dump(results, out_f, app=app, indent=indent)
