import toml
import os
import asyncio
import weakref

import carb
import carb.settings
import carb.tokens
import omni.client
import omni.kit.app
import omni.kit.ui
import omni.ext
from omni import ui

WINDOW_NAME = "About"


class PrivacyWindow:
    def __init__(self, privacy_file=None):
        if not privacy_file:
            privacy_file = carb.tokens.get_tokens_interface().resolve("${omni_config}/privacy.toml")

        privacy_data = toml.load(privacy_file) if os.path.exists(privacy_file) else {}

        # NVIDIA Employee?
        privacy_dict = privacy_data.get("privacy", {})
        userId = privacy_dict.get("userId", None)
        if not userId or not userId.endswith("@nvidia.com"):
            return

        # Already set?
        extraDiagnosticDataOptIn = privacy_dict.get("extraDiagnosticDataOptIn", None)
        if extraDiagnosticDataOptIn:
            return

        self._window = ui.Window(
            "Privacy",
            flags=ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE,
            auto_resize=True,
        )

        def on_ok_clicked():
            allow_for_public_build = self._cb.model.as_bool

            carb.log_info(f"writing privacy file: '{privacy_file}'. allow_for_public_build: {allow_for_public_build}")
            privacy_data.setdefault("privacy", {})["extraDiagnosticDataOptIn"] = (
                "externalBuilds" if allow_for_public_build else "internalBuilds"
            )
            with open(privacy_file, "w") as f:
                toml.dump(privacy_data, f)
            self._window.visible = False

        text = """
By accessing or using Omniverse Beta, you agree to share usage and performance data as well as diagnostic data, including crash data.  This will help us to optimize our features, prioritize development, and make positive changes for future development.

As an NVIDIA employee, your email address will be associated with any collected diagnostic data from internal builds to help us improve Omniverse.  Below, you can optionally choose to associate your email address with any collected diagnostic data from publicly available builds.  Please contact us at omniverse-license-questions@nvidia.com for any questions.
"""
        with self._window.frame:
            with ui.ZStack(width=0, height=0):
                with ui.VStack(style={"margin": 5}, height=0):
                    ui.Label(text, width=600, style={"font_size": 18}, word_wrap=True)
                    ui.Separator()

                    with ui.HStack(height=0):
                        self._cb = ui.CheckBox(width=0, height=0)
                        self._cb.model.set_value(True)
                        ui.Label(
                            "Associate my @nvidia.com email address with diagnostic data from publicly available builds.'",
                            value=True,
                            style={"font_size": 16},
                        )
                    with ui.HStack(height=0):
                        ui.Spacer()
                        ui.Button("OK", width=100, clicked_fn=lambda: on_ok_clicked())
                        ui.Spacer()

        self._window.visible = True
        self.on_ok_clicked = on_ok_clicked


async def _create_window(ext_weak):
    # Wait for few frames to get everything in working state first
    for _ in range(5):
        await omni.kit.app.get_app().next_update_async()
    if ext_weak():
        ext_weak()._window = PrivacyWindow()


class Extension(omni.ext.IExt):
    def on_startup(self, ext_id):
        asyncio.ensure_future(_create_window(weakref.ref(self)))

    def on_shutdown(self):
        self._window = None

