from typing import Optional
from typing import Any


async def get_upload_instance(
    api_func, simulation_pk: int, filename: str
) -> Optional[Any]:
    """
    Get the uploaded file instance based on filename

    api_func should be an async API function to list a
    file upload instance
    """
    offset: int = 0
    limit: int = 10

    found = None
    next: bool = True

    while not found and next:
        res = await api_func(simulation_pk=simulation_pk, offset=offset, limit=limit)
        results = [x for x in res.results if x.file.filename == filename]

        if results:
            found = results[0]
            break

        # Make sure AsyncMock used in unit-tests are not evaluated as true
        next = res.next is not None and isinstance(res.next, str) and len(res.next) != 0
        offset += 10
        limit += 10

    return found