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 resize_file


class GetResizedFile(View):
    """
    returns binary file after resizing
    """
    # pylint: disable=arguments-differ
    methods = ['GET']


    def dispatch_request(self, file_id: int, resolution: 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 resolution
        resolution = re.split(r'[^0-9]', resolution)
        max_width = int(resolution[0])
        max_height = int(resolution[1]) if len(resolution) > 1 else 2 ** 24

        # resize file
        file_directory, file_name = tpool.execute(resize_file, file, project.root_folder,
                                                  max_width, max_height)

        # send to client
        return send_from_directory(file_directory, file_name)