import os
import re

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

from pycs.database.File import File
from pycs.util.FileOperations import BoundingBox
from pycs.util.FileOperations import crop_file


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


    def dispatch_request(self, file_id: int, resolution: str, crop_box: str):
        # get file from database
        file = File.get_or_404(file_id)

        project = file.project

        if not os.path.exists(file.absolute_path):
            abort(404, "File not found!")

        # extract desired crop
        resolution = re.split(r'[^0-9]', resolution)
        max_width = int(resolution[0])
        max_height = int(resolution[1]) if len(resolution) > 1 else 2 ** 24

        crop_box = re.split(r'[^0-9.]', crop_box)
        crop_x = float(crop_box[0])
        crop_y = float(crop_box[1]) if len(crop_box) > 1 else 0
        crop_w = float(crop_box[2]) if len(crop_box) > 2 else 1 - crop_x
        crop_h = float(crop_box[3]) if len(crop_box) > 3 else 1 - crop_y

        box = BoundingBox(x=crop_x, y=crop_y, w=crop_w, h=crop_h)
        # crop file
        file_directory, file_name = tpool.execute(crop_file, file, project.root_folder,
                                                  box, max_width, max_height)

        # send to client
        return send_from_directory(file_directory, file_name)
