## Copyright (c) 2021, 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 omni.kit.test
from pathlib import Path
from omni.kit.search_core import SearchEngineRegistry
from ..search_model import SearchModel
from ..search_model import SearchItem
import asyncio
from functools import partial

CURRENT_PATH = Path(__file__).parent


async def _wait_model_changed_async(model: SearchModel):
    """Async wait when the model is changed"""

    def _on_item_changed(item: SearchItem, future: asyncio.Future):
        """Callback set the future when called"""
        if not future.done():
            future.set_result(None)

    f = asyncio.Future()
    sub = model.subscribe_item_changed(partial(_on_item_changed, future=f))
    return await f


class TestSearchExample(omni.kit.test.AsyncTestCase):
    async def test_search(self):
        model_type = SearchEngineRegistry().get_search_model("Example Search")
        self.assertIs(model_type, SearchModel)

        model = model_type(search_text="test", current_dir=f"{CURRENT_PATH}")
        await _wait_model_changed_async(model)

        # In the current folder we only have the file "test_search_example.py"
        self.assertEqual(["test_search_example.py"], [item.name for item in model.items])
