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

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


class CopyResults(View):
    """
    copy all results for one file to another
    """
    # pylint: disable=arguments-differ
    methods = ['POST']

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

    def dispatch_request(self, file_id: int):

        file = File.get_or_404(file_id)
        request_data = request.get_json(force=True)

        if 'copy_from' not in request_data:
            abort(400, "copy_from argument is missing")

        other_file = File.get_or_404(request_data.get('copy_from'))

        new = []
        # start transaction
        with db.session.begin_nested():

            for result in other_file.results.all():
                new_result = file.create_result(
                    origin='pipeline',
                    result_type=result.type,
                    label=result.label,
                    data=result.data,
                    commit=False)
                new.append(new_result)


        for new_result in new:
            self.nm.create_result(new_result)

        return make_response()
