import fsspec
from typing import Optional
from typing import Set
from typing import List


def _get_objects_in_path(
        fs: fsspec.AbstractFileSystem,
        path: str,
        target_type: Optional[str] = None,
        extensions: Optional[Set[str]] = None
) -> List[str]:
    """Get all objects of a specific type in the supplied path on the target file system.
    
    """
    result = []
    
    if target_type is not None:
        # List all objects with detailed information.
        files = fs.ls(path, detail=True)  # type: List[dict]

        for entry in files:
            if entry.get("type") != target_type:
                continue
            
            result.append(entry.get("name"))
    else:
        # List all objects without detailed information.
        result = fs.ls(path, detail=False)

    # If extensions are supplied, apply these as well.
    if extensions is not None:
        entries = result
        result = []
        
        for entry in entries:
            try:
                base, ext = entry.rsplit(".", 1)
            except ValueError:
                continue

            if ext.lower() not in extensions:
                continue
            
            result.append(entry)
    
    # Assume the files have a counter in the file name, such that the sorted list is the correct ordering.
    return sorted(result)