from os import remove

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

from pycs.database.Database import Database
from pycs.frontend.notifications.NotificationManager import NotificationManager


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

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

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

        if 'remove' not in data or data['remove'] is not True:
            return abort(400)

        # start transaction
        with self.db:
            # find file
            file = self.db.file(identifier)
            if file is None:
                return abort(400)

            # check if project uses an external data directory
            project = file.project()
            if project.external_data:
                return abort(400)

            # remove file from database
            file.remove()

            # remove file from folder
            remove(file.path)

            # TODO remove temp files

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