#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utils for handling files and folders."""

import os

from glob import glob


def get_latest_folder(path: str, filter_substr: str = None) -> str:
    """Gets latest folder by timest

    Args:
        path: Path to parent directory where to search for latest folder
        filter_substr: If only certain set of folders need to be selected based on a substring match, defaults to None

    Returns:
        str: File path
    """
    files_and_folders = list(glob(os.path.join(path, "*")))
    if filter_substr:
        files_and_folders = [
            path for path in files_and_folders if filter_substr in path
        ]
    folder_paths = [path for path in files_and_folders if os.path.isdir(path)]
    recent_folder_path = max(folder_paths, key=os.path.getctime)
    return recent_folder_path


def list_files(startpath: str) -> list:
    """Lists all files in a directory

    Args:
        startpath: Path to directory

    Returns:
        list: List of files
    """
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, "").count(os.sep)
        indent = " " * 4 * (level)
        print("{}{}/".format(indent, os.path.basename(root)))
        subindent = " " * 4 * (level + 1)
        for f in files:
            print("{}{}".format(subindent, f))
