from flask import abort, jsonify
from flask.views import View

from pycs.database.Database import Database


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

    def __init__(self, db: Database):
        # pylint: disable=invalid-name
        self.db = db

    def dispatch_request(self, project_id: int):
        # find project
        project = self.db.project(project_id)

        if project is None:
            return abort(404)

        # get collection list
        collections = project.collections()

        # disable autoselect if there are no elements in the collection
        found = False

        for collection in collections:
            if collection.autoselect:
                if found:
                    collection.autoselect = False
                elif collection.count_files() == 0:
                    collection.autoselect = False
                    found = True

        # return files
        return jsonify(collections)
