from shutil import rmtree

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 RemoveProject(View):
    """
    remove a project from database and remove its directory
    """
    # 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:
            abort(400)

        # start transaction
        with self.db:
            # find project
            project = self.db.project(identifier)
            if project is None:
                abort(404)

            # remove from database
            project.remove()

            # remove model from database
            model = project.model()
            model.remove()

            # remove from file system
            rmtree(project.root_folder)

            # send update
            self.nm.remove_model(model)
            self.nm.remove_project(project)

            return make_response()
