import carb
from pxr import Sdf, Usd, UsdGeom, UsdShade

## this is a placeholder for Usd.Attribute as that class cannot be created unless attached to a prim


class PlaceholderAttribute:
    def __init__(self, name, prim: Usd.Prim = None, metadata=None):
        self._name = name
        self._prim = prim
        self._metadata = metadata if metadata else {}

    def Get(self, time_code=0):
        if self._metadata:
            custom_data = self._metadata.get("customData")
            if custom_data is not None and "default" in custom_data:
                return custom_data["default"]

            default = self._metadata.get("default")
            if default is not None:
                return default

        carb.log_warn(f"PlaceholderAttribute.Get() customData.default or default not found in metadata")
        return None

    def GetPath(self):
        if self._prim:
            return self._prim.GetPath()
        return None

    def ValueMightBeTimeVarying(self):
        return False

    def GetMetadata(self, token):
        if token in self._metadata:
            return self._metadata[token]
        return False

    def GetAllMetadata(self):
        return self._metadata

    def GetPrim(self):
        return self._prim

    def CreateAttribute(self):
        try:
            if not self._name:
                carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no attribute name")
                return None

            if not self._prim:
                carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no target prim")
                return None

            type_name_key = self._metadata.get(Sdf.PrimSpec.TypeNameKey)
            if not type_name_key:
                carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error TypeNameKey")
                return None

            type_name = Sdf.ValueTypeNames.Find(type_name_key)

            if self._name.startswith("primvars:"):
                pv = UsdGeom.PrimvarsAPI(self._prim)
                attribute = UsdGeom.PrimvarsAPI(self._prim).CreatePrimvar(self._name[9:], type_name).GetAttr()
            elif self._name.startswith("inputs:"):
                shader = UsdShade.Shader(self._prim)
                attribute = shader.CreateInput(self._name[7:], type_name).GetAttr()
            else:
                attribute = self._prim.CreateAttribute(self._name, type_name, custom=False)

            filter = {"customData", "displayName", "displayGroup", "documentation"}
            if attribute:
                for key in self._metadata:
                    if key not in filter:
                        attribute.SetMetadata(key, self._metadata[key])
                attribute.Set(self.Get())

            return attribute
        except Exception as exc:
            carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error {exc}")
        return None

    def HasAuthoredConnections(self):
        return False
