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

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


class RemoveLabel(View):
    """
    remove a label from database
    """
    # 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, project_id: int, label_id: int):
        # extract request data
        data = request.get_json(force=True)

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

        # find project
        project = self.db.project(project_id)
        if project is None:
            abort(404)

        # find label
        label = project.label(label_id)
        if label is None:
            abort(404)

        # find children
        children = label.children()

        # start transaction
        with self.db:
            # remove children's parent entry
            for child in children:
                child.set_parent(None)
                self.nm.edit_label(child)

            # remove label
            label.remove()
            self.nm.remove_label(label)

        # return success response
        return make_response()
