import carb

def _trans_color(color):
    if isinstance(color, (list, tuple)):
        if len(color) == 3:
            return carb.Float4(color[0], color[1], color[2], 1.0)
        elif len(color) == 4:
            return carb.Float4(color[0], color[1], color[2], color[3])
    elif isinstance(color, str):
        argb_int = int(color, 16)
        r = ((argb_int >> 16) & 0x000000FF) / 255.0
        g = ((argb_int >> 8) & 0x000000FF) / 255.0
        b = (argb_int & 0x000000FF) / 255.0
        w = ((argb_int >> 24) & 0x000000FF) / 255.0
        return carb.Float4(r, g, b, w)
    elif isinstance(color, float):
        return carb.Float4(color, color, color, 1.0)
    else:
        return None


def setup_imgui():
    settings = carb.settings.get_settings()

    import omni.kit.imgui as _imgui
    imgui = _imgui.acquire_imgui()

    imgui_configs = settings.get("/exts/omni.app.setup/imgui")

    if not imgui_configs:
        return

    colors = imgui_configs.get("color", {})
    if colors:
        for name, value in colors.items():
            color = _trans_color(value)
            if color:

                def _push_color(imgui, name, color):
                    try:
                        source = f"imgui.push_style_color(carb.imgui.StyleColor.{name}, {color})"
                        carb.log_info(f"config style color {name} tp {color}")
                        exec(source)
                    except Exception as e:
                        carb.log_error(f"Failed to config imgui style color {name} to {color}: {e}")

                _push_color(imgui, name, color)
            else:
                carb.log_error(f"Unknown color format for {name}: {value}")

    floats = imgui_configs.get("float", {})
    if floats:
        for name, value in floats.items():
            if value != "":

                def _push_float_var(imgui, name, value):
                    try:
                        source = f"imgui.push_style_var_float(carb.imgui.StyleVar.{name}, {value})"
                        carb.log_info(f"config float var {name} tp {value}")
                        exec(source)
                    except Exception as e:
                        carb.log_error(f"Failed to config imgui float var {name} to {color}: {e}")

                _push_float_var(imgui, name, value)
