"""
Contains support for testing methods in ../scripts/register_ogn_nodes
"""
import os
from pathlib import Path
from tempfile import TemporaryDirectory

import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn

from .._impl.register_ogn_nodes import find_import_locations


class TestRegisterOgnNodes(ogts.OmniGraphTestCase):
    """Unit test class"""

    # --------------------------------------------------------------------------------------------------------------
    def test_find_import_locations(self):
        """Test for the utility function find_import_locations
        Test data consists of list of (inputs, outputs, failure):
          inputs (2-tuple):
            Path to file calling the scripts
            Python import path for the extension
          outputs (2-tuple):
            Expected location of the import path's root directory
            Expected location of the calling file's directory
          failure (bool):
            Should the test raise an exception?
        """
        no_exception = False
        exception = True
        drive = "C:" if os.name == "nt" else "/drive"
        test_data = [
            [(f"{drive}/a/b/c/d.py", "b.c"), (f"{drive}/a", f"{drive}/a/b/c"), no_exception],
            [(f"{drive}/a/b/c/d.py", "b.c.d"), (), exception],
        ]

        for (index, test_run) in enumerate(test_data):
            if test_run[2]:
                with self.assertRaises(ValueError, msg=f"Expected failure in test {index} - {test_run}"):
                    _ = find_import_locations(test_run[0][0], test_run[0][1])
            else:
                results = find_import_locations(test_run[0][0], test_run[0][1])
                self.assertEqual(results[0], test_run[1][0], f"Import root for {test_run}")
                self.assertEqual(results[1], test_run[1][1], f"Generated directory for {test_run}")

    # --------------------------------------------------------------------------------------------------------------
    def test_generate_automatic_test_imports(self):
        """Test for the utility function generate_automatic_test_imports
        Test data consists of list of (test_files, output, should_modify):
        inputs (List[str]):
            List of test file names to create
        output (str):
            Expected contents of __init__.py
        should_modify (bool):
            Should the test have modified __init__.py
        """
        full_test_file = ogn.import_file_contents()
        test_data = [
            [],  # Generate an empty init file if no tests are available
            ["TestOgnTest1.py"],  # Add a new test case
            ["TestOgnTest1.py"],  # No new testcases so no changes should be made
            ["TestOgnTest1.py", "TestOgnTest2.py"],  # Add a new test case
            [],  # No testcases leaves the file in place
        ]

        # Set up temporary test directory
        with TemporaryDirectory() as test_directory_fd:
            test_directory = Path(test_directory_fd)
            import_filepath = test_directory / "__init__.py"

            for test_run, test_files in enumerate(test_data):
                # Create empty test files
                for file in test_files:
                    with open(test_directory / file, "a", encoding="utf-8"):
                        pass

                ogn.generate_test_imports(test_directory, write_file=True)

                # Verify __init__.py contents
                with open(import_filepath, "r", encoding="utf-8") as import_fd:
                    self.assertCountEqual(
                        [line.rstrip() for line in import_fd.readlines()],
                        full_test_file,
                        f"Generated incorrect test import file for run {test_run}",
                    )

                # Delete generated test files to prepare for the next test
                for file in test_directory.glob("TestOgn*.py"):
                    file.unlink()
