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

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


class CreateResult(View):
    """
    create a result for a file
    """
    # 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, file_id: int):
        # extract request data
        request_data = request.get_json(force=True)

        if 'type' not in request_data:
            return abort(400)
        if request_data['type'] not in ['labeled-image', 'bounding-box']:
            return abort(400)

        rtype = request_data['type']

        if 'label' in request_data and request_data['label']:
            label = request_data['label']
        elif request_data['type'] == 'labeled-image':
            return abort(400)
        else:
            label = None

        if 'data' in request_data and request_data['data']:
            data = request_data['data']
        elif request_data['type'] == 'bounding-box':
            return abort(400)
        else:
            data = {}

        # find file
        file = self.db.file(file_id)
        if file is None:
            return abort(404)

        # start transaction
        with self.db:
            # find full-image labels and remove them
            for result in file.results():
                if result.type == 'labeled-image':
                    result.remove()
                    self.nm.remove_result(result)

            # insert into database
            result = file.create_result('user', rtype, label, data)
            self.nm.create_result(result)

        return jsonify(result)
