import asyncio
import shutil
import sys
import time

from clarabot_nano_tests.testing.file import rmtree_except


async def delay_retry_coroutine_assertion(coro, *args, retry=8, delay=0.05, **kwargs):
    i = 0
    while True:
        try:
            await coro(*args, **kwargs)
        except AssertionError:
            i += 1
            if i > retry:
                raise
            await asyncio.sleep(delay)
        else:
            break


def alt_temp_dir() -> str:
    if sys.platform.startswith("win"):
        # The official temporary directory is in the depths of the user's AppData, which is sensitive.
        return "C:\\tmp"
    # The temporary directory may be sensitive (on darwin for example: /var/folders/*).
    return "/tmp"


def clear_nano_app_config_data_dir(config_dir, data_dir):
    i = 0
    while True:
        try:
            if config_dir.exists():
                shutil.rmtree(config_dir)
            rmtree_except(data_dir, {"pid": None})
            break
        except PermissionError:
            if not sys.platform.startswith("win") or i == 4:
                raise
            time.sleep(0.5)
            i += 1
