import os
import os.path
import asyncio
import carb
import omni.kit.app


def clean_files_in_directory(directory, suffix):
    if not os.path.exists(directory):
        return
    images = os.listdir(directory)
    for item in images:
        if item.endswith(suffix):
            os.remove(os.path.join(directory, item))


def make_sure_directory_existed(directory):
    if not os.path.exists(directory):
        try:
            os.makedirs(directory, exist_ok=True)
        except OSError as error:
            carb.log_warn(f"Directory cannot be created: {dir}")
            return False
    return True

# TODO: Remove this as it is no longer used, but kept only if transitively depended on
#
def is_kit_104_and_above():
    kit_version = omni.kit.app.get_app().get_build_version().split(".")
    try:
        major_ver = int(kit_version[0])
        return major_ver >= 104
    except Exception as e:
        return False


async def wait_for_image_writing(image_path, seconds_to_wait: float = 30, seconds_to_sleep: float = 0.5):
    seconds_tried = 0.0
    carb.log_info(f"Waiting for {image_path} to be written to disk.")
    while seconds_tried < seconds_to_wait:
        if os.path.isfile(image_path) and os.access(image_path, os.R_OK):
            carb.log_info(f"{image_path} is written to disk in {seconds_tried}s.")
            break
        else:
            await asyncio.sleep(seconds_to_sleep)
            seconds_tried += seconds_to_sleep

    if seconds_tried >= seconds_to_wait:
        carb.log_warn(f"Waiting for {image_path} timed out..")
