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.Project import Project
from pycs.frontend.notifications.NotificationManager import NotificationManager


class CreateLabel(View):
    """
    create a new label
    """
    # pylint: disable=arguments-differ
    methods = ['POST']

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


    def dispatch_request(self, project_id):
        # extract request data
        data = request.get_json(force=True)
        name = data.get('name')

        if name is None:
            abort(400)

        name = data['name']
        reference = data.get('reference')
        parent = data.get('parent')

        # find project
        project = Project.get_or_404(project_id)

        # insert label
        with db.session.begin_nested():
            label, is_new = project.create_label(
                name=name,
                reference=reference,
                parent=parent,
                commit=False)
            if not is_new:
                abort(400, f"Label already exists: {label}")

        # send notification
        self.nm.create_label(label)

        # return success response
        return make_response()
