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

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


class EditResultLabel(View):
    """
    edit a result and set its label
    """
    # pylint: disable=arguments-differ
    methods = ['POST']

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

    def dispatch_request(self, result_id: int):
        # find result
        result = Result.get_or_404(result_id)

        # extract request data
        request_data = request.get_json(force=True)

        if 'label' not in request_data:
            abort(400, "Could not find label argument!")

        label = request_data.get('label')

        # abort if label is empty for labeled-images
        if result.type == 'labeled-image' and label is None:
            abort(400, "Label is required for 'labeled-images' results")

        result.label_id = label
        result.set_origin('user', commit=True)

        self.nm.edit_result(result)
        return make_response()
