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

from pycs.database.Project import Project


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


    def dispatch_request(self,
                         project_id: int,
                         start: int = 0,
                         length: int = -1,
                         collection_id: int = None):
        # find project

        project = Project.get_or_404(project_id)

        # get count and files
        if collection_id is not None:
            if collection_id == 0:
                count = project.count_files_without_collection()
                files = project.files_without_collection(offset=start, limit=length)

            else:
                collection = project.collection(collection_id)
                if collection is None:
                    abort(404)

                count = collection.files.count()
                files = collection.get_files(offset=start, limit=length).all()

        else:
            count = project.files.count()
            files = project.get_files(offset=start, limit=length).all()

        # return files
        return jsonify({
            'count': count,
            'files': files
        })
