from os import path, getcwd

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

from pycs.database.Database import Database


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

    def __init__(self, db: Database):
        # pylint: disable=invalid-name
        self.db = db

    def dispatch_request(self, file_id: int):
        # get file from database
        file = self.db.file(file_id)

        if file is None:
            return abort(404)

        # get absolute path
        if path.isabs(file.path):
            abs_file_path = file.path
        else:
            abs_file_path = path.join(getcwd(), file.path)

        # return data
        file_directory, file_name = path.split(abs_file_path)
        return send_from_directory(file_directory, file_name)
