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

from pycs.database.Database import Database


class ListFiles(View):
    """
    return a list of files 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, start: int, length: int, collection_id: int = None):
        # find project
        project = self.db.project(project_id)
        if project is None:
            return abort(404)

        # get count and files
        if collection_id is not None:
            if collection_id == 0:
                count = project.count_files_without_collection()
                files = list(project.files_without_collection(start, length))
            else:
                collection = project.collection(collection_id)
                if collection is None:
                    return abort(404)

                count = collection.count_files()
                files = list(collection.files(start, length))
        else:
            count = project.count_files()
            files = list(project.files(start, length))

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