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

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


class RemoveLabel(View):
    """
    remove a label from database
    """
    # pylint: disable=arguments-differ
    methods = ['POST']

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

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

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

        # find label
        label = Label.query.filter(
            Label.project_id == project_id,
            Label.id == label_id).one_or_none()

        if label is None:
            abort(404)

        # start transaction
        with db.session.begin_nested():

            children = label.children
            # remove label. because of cascade, parent_id is set ot NULL
            label_dump = label.delete(commit=False)
            label.flush()

            # notify about changes and reset the parent
            for child in children:
                child.parent_id = label.parent_id
                self.nm.edit_label(child)

            self.nm.remove_label(label_dump)

        # return success response
        return make_response()
