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,
                         user: str,
                         project_id: int,
                         start: int = 0,
                         length: int = -1,
                         collection_id: int = None):
        # pylint: disable=unused-argument
        # 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:

            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"

            # first get all files without specific limit
            files = project.get_files(**kwargs)
            # get the count of those
            count = files.count()
            # finally, limit to the desired offset and number of files
            files = files.offset(start).limit(length).all()

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