from flask import make_response, request, abort
from flask.views import View

from pycs import db
from pycs.database.File import File
from pycs.frontend.notifications.NotificationManager import NotificationManager


class RemoveFile(View):
    """
    remove a given file
    """
    # pylint: disable=arguments-differ
    methods = ['POST']

    def __init__(self, nm: NotificationManager):
        # pylint: disable=invalid-name
        self.nm = nm

    def dispatch_request(self, file_id: int):
        # extract request data
        data = request.get_json(force=True)

        if not data.get('remove', False):
            abort(400, "remove flag is missing")

        # start transaction
        with db.session.begin_nested():
            # find file
            file = File.get_or_404(file_id)

            # check if project uses an external data directory
            if file.project.external_data:
                abort(400,
                    "Cannot remove file, project is setup with external data!")

            # remove file from database
            file_dump = file.delete()

        # send notification
        self.nm.remove_file(file_dump)
        return make_response()
