from django.http import HttpResponseBase, HttpRequest, Http404
from django.core.exceptions import PermissionDenied
from django.conf import settings
from resources.acl import UserAccess
from resources.models import Resource, Project
from rpc.fileresponse import RangedFileResponse
import os
from pathlib import Path


def file_passthru_noauth(request: HttpRequest, path: str) -> HttpResponseBase:
    try:
        file_hash = path[6:70]
        resource_instance = Resource.objects.get(
            file__hash=file_hash,
        )
        tested_path = os.path.realpath(Path(settings.HLS_DIR, path))
        if not tested_path.startswith(settings.HLS_DIR):
            raise PermissionDenied()
        if not Path(tested_path).exists():
            raise Http404()
        return RangedFileResponse(
            request,
            open(tested_path, "rb"),
            content_type=resource_instance.file.file_type.mime,
        )
    except Resource.DoesNotExist:
        raise Http404()


def file_passthru_auth(request: HttpRequest, path: str) -> HttpResponseBase:
    if not request.user.is_anonymous:
        file_hash = path[6:70]
        for project_instance in Project.objects.filter(
            projectaccess__user=request.user, file__hash=file_hash
        ).distinct():
            resource_instance = Resource.objects.get(
                ptr_project=project_instance,
                file__hash=file_hash,
                ptr_project__projectaccess__user=request.user,
            )
            if UserAccess(request.user, project_instance).can_read(resource_instance):
                tested_path = os.path.realpath(Path(settings.HLS_DIR, path))
                if not tested_path.startswith(settings.HLS_DIR):
                    raise PermissionDenied()
                if not Path(tested_path).exists():
                    raise Http404()
                return RangedFileResponse(
                    request,
                    open(tested_path, "rb"),
                    content_type=resource_instance.file.file_type.mime,
                )
    raise PermissionDenied()


def file_passthru(request: HttpRequest, path: str) -> HttpResponseBase:
    if settings.HLS_URLS_NEED_AUTH:
        return file_passthru_auth(request, path)
    else:
        return file_passthru_noauth(request, path)
