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 CreateLabel(View):
    """
    create a new label
    """
    # 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 'name' not in data:
            abort(400)

        name = data['name']
        parent = data['parent'] if 'parent' in data else None

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

        # start transaction
        with self.db:
            # insert label
            label, _ = project.create_label(name, parent_id=parent)

        # send notification
        self.nm.create_label(label)

        # return success response
        return make_response()
