from flask import abort
from flask import jsonify
from flask import request
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()


            with_annotations = request.args.get("only_with_annotations")

            kwargs = dict(with_annotations=None)

            if with_annotations is not None:
                kwargs["with_annotations"] = with_annotations == "1"

            files = project.get_files(offset=start, limit=length, **kwargs).all()

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