import tempfile
import toml

import omni.kit.test
import omni.kit.window.privacy


class TestPrivacyWindow(omni.kit.test.AsyncTestCase):
    async def test_privacy(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            privacy_file = f"{tmp_dir}/privacy.toml"
            def write_data(data):
                with open(privacy_file, "w") as f:
                    toml.dump(data, f)

            # NVIDIA User, first time
            write_data({"privacy": {"userId": "bob@nvidia.com"}})

            w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
            self.assertIsNotNone(w._window)
            w.on_ok_clicked()

            data = toml.load(privacy_file)
            self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "externalBuilds")

            # NVIDIA User, second time
            w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
            self.assertFalse(hasattr(w, "_window"))

            # NVIDIA User, first time, checkbox off
            write_data({"privacy": {"userId": "bob@nvidia.com"}})

            w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
            self.assertIsNotNone(w._window)
            w._cb.model.set_value(False)
            w.on_ok_clicked()

            data = toml.load(privacy_file)
            self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "internalBuilds")

            # Non NVIDIA User
            write_data({"privacy": {"userId": "bob@zzzzz.com"}})
            w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
            self.assertFalse(hasattr(w, "_window"))
