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

from pycs.database.Database import Database
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, db: Database, nm: NotificationManager):
        # pylint: disable=invalid-name
        self.db = db
        self.nm = nm

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

        if 'label' not in data:
            return abort(400)

        # find result
        result = self.db.result(result_id)
        if result is None:
            return abort(404)

        # abort if label is empty for labeled-images
        if result.type == 'labeled-image' and not data['label']:
            return abort(400)

        # start transaction and set label
        with self.db:
            result.set_label(data['label'])
            result.set_origin('user')

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