## Copyright (c) 2023, NVIDIA CORPORATION.  All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto.  Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##

import carb.settings
import omni.kit.app
from omni.kit.test import AsyncTestCase
import omni.rtx.ovtextureconverter.scripts.commands as commands

import asyncio
import os
import os.path
import pathlib
import shutil

TEST_DATA_DIR = str(pathlib.Path(__file__).parent.joinpath("data"))
TEST_OUTPUT_DIR = omni.kit.test.get_test_output_path()

class TestCommands(AsyncTestCase):
    async def setUp(self):
        pass

    async def tearDown(self):
        pass

    async def test_IssueTextureCompressionRequest(self):
        """
        Test Command to create texture caches with new UJITSO build system
        """
        source_texture = pathlib.Path(TEST_DATA_DIR, "dot.png")
        tex_cache_dir = pathlib.Path(TEST_OUTPUT_DIR, "ujitso_texcache")

        settings = carb.settings.get_settings()
        self.assertTrue(settings.get_as_bool("/rtx-transient/resourcemanager/UJITSO/enabled"))

        # Set the destination for texture caching
        settings.set_string("/rtx-transient/resourcemanager/remoteTextureCachePath", str(tex_cache_dir))

        # Clear the local texture cache path to allow repeated tests, otherwise only works first time.
        settings.set_string("/rtx-transient/resourcemanager/localTextureCachePath", "")

        # Disable omnihub
        settings.set_bool("/rtx-transient/resourcemanager/useOmniHubCache", False)
        settings.set_bool("/rtx-transient/resourcemanager/useMDBCache", False)

        # Remove results from any previous run
        if os.path.exists(tex_cache_dir):
            shutil.rmtree(tex_cache_dir)

        cmd = commands.IssueTextureCompressionRequest(path=str(source_texture))
        self.assertTrue(cmd.do())

        # NOTE: the datastore that handles the upload currently has no way to wait for all uploads to complete.
        print("Waiting for UJITSO texture uploads...")
        await asyncio.sleep(5)

        self.assertTrue(os.path.exists(tex_cache_dir))
        files = os.listdir(tex_cache_dir)
        self.assertTrue(len(files) > 0)
