from flask import jsonify
from flask.views import View

from pycs.database.Project import Project


class ListLabelTree(View):
    """
    return a list of labels for a given project
    """
    # pylint: disable=arguments-differ
    methods = ['GET']


    def dispatch_request(self, project_id):
        # find project
        project = Project.get_or_404(project_id)

        labels = [lab.serialize() for lab in project.labels.all()]

        lookup = {}
        for label in labels:
            label["children"] = []
            lookup[label["id"]] = label

        tree = []
        for label in labels:
            parent_id = label["parent_id"]
            if parent_id is None:
                tree.append(label)
            else:
                lookup[parent_id]["children"].append(label)

        return jsonify(tree)
