import os

from flask import abort
from flask import send_from_directory
from flask.views import View

from pycs.database.Result import Result
from pycs.util import file_ops


class ResultAsCrop(View):
    """
    return the image crop defined by the result.
    """
    # pylint: disable=arguments-differ
    methods = ['GET']


    def dispatch_request(self, result_id: int, max_width: int = 2**24, max_height: int = 2**24):

        # find result
        result = Result.get_or_404(result_id)

        if result.type != "bounding-box":
            msg = f"The type of the queried result was not \"bounding-box\"! It was {result.type}"
            abort(400, msg)

        file = result.file

        if file.type != "image":
            abort(400, "Currently only supporting images!")


        data = result.data

        if data is None:
            abort(400, "The data of the result was None!")

        xywh = [data.get(attr, -1) for attr in "xywh"]
        if -1 in xywh:
            abort(400, f"The data of the result is not correct: {data}!")


        crop_path, crop_fname = file_ops.crop_file(file, file.project.root_folder, *xywh)

        parts = os.path.splitext(crop_fname)

        crop_new_fname = f"{parts[0]}_{max_width}_{max_height}.{parts[1]}"

        resized = file_ops.resize_image(
            os.path.join(crop_path, crop_fname),
            os.path.join(crop_path, crop_new_fname),
            max_width,
            max_height
        )

        if resized:
            crop_fname = crop_new_fname

        return send_from_directory(crop_path, crop_fname)
