use std::any::TypeId;
use crate::{InteropError, static_type::registered_type_info};
use bevy_mod_scripting_world::WorldGuard;
use bevy_reflect::{PartialReflect, Reflect, ReflectRef, TypeInfo, enums::VariantInfo};
#[derive(Clone, Copy, Reflect, Debug, PartialEq)]
pub struct EnumVariantRef {
pub type_id: TypeId,
pub variant_index: usize,
}
impl EnumVariantRef {
pub fn from_name(type_info: &'static TypeInfo, name: &str) -> Option<Self> {
let variant_index = match type_info {
TypeInfo::Enum(info) => info.index_of(name)?,
_ => return None,
};
Some(Self {
type_id: type_info.type_id(),
variant_index,
})
}
pub fn from_value(type_id: TypeId, value: &dyn PartialReflect) -> Option<Self> {
match value.reflect_ref() {
ReflectRef::Enum(e) => Some(Self {
type_id,
variant_index: e.variant_index(),
}),
_ => None,
}
}
pub fn type_info(&self, world: &WorldGuard) -> Result<&'static TypeInfo, InteropError> {
registered_type_info(world, self.type_id)
}
pub fn info(&self, world: &WorldGuard) -> Result<&'static VariantInfo, InteropError> {
match self.type_info(world)? {
TypeInfo::Enum(info) => info.variant_at(self.variant_index),
_ => None,
}
.ok_or_else(|| {
InteropError::invariant("enum variant reference points to a missing variant")
})
}
pub fn variant_name(&self, world: &WorldGuard) -> Result<&'static str, InteropError> {
self.info(world).map(|info| info.name())
}
}