import os
import re
import pathlib
from pxr import Sdf, Tf
from typing import List
from omni.kit.window.drop_support import ExternalDragDrop

external_drag_drop = None


def setup_external_drag_drop(window_name :str):
    global external_drag_drop
    destroy_external_drag_drop()
    external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=_on_ext_drag_drop)


def destroy_external_drag_drop():
    global external_drag_drop
    if external_drag_drop:
        external_drag_drop.destroy()
        external_drag_drop = None


def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str]):
    import omni.usd
    import omni.kit.undo
    import omni.kit.commands

    default_prim_path = Sdf.Path("/")
    stage = omni.usd.get_context().get_stage()
    if stage.HasDefaultPrim():
        default_prim_path = stage.GetDefaultPrim().GetPath()

    re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE)
    re_usd = re.compile(r"^.*\.(usd|usda|usdc|usdz)(\?.*)?$", re.IGNORECASE)

    for source_url in edd.expand_payload(payload):
        if re_usd.match(source_url):
            try:
                import omni.kit.window.file
                omni.kit.window.file.open_stage(source_url.replace(os.sep, '/'))
            except ImportError:
                import carb
                carb.log_warn(f'Failed to import omni.kit.window.file - Cannot open stage {source_url}')
            return

    with omni.kit.undo.group():
        for source_url in edd.expand_payload(payload):
            if re_audio.match(source_url):
                stem = pathlib.Path(source_url).stem
                path = default_prim_path.AppendChild(Tf.MakeValidIdentifier(stem))
                omni.kit.commands.execute(
                    "CreateAudioPrimFromAssetPath",
                    path_to=path,
                    asset_path=source_url,
                    usd_context=omni.usd.get_context(),
                )
