use std::{any::TypeId, collections::VecDeque};
use bevy_mod_scripting_world::{CallScope, WorldGuard};
use bevy_platform::collections::HashMap;
use bevy_reflect::TypeRegistry;
use super::{
arg_meta::ArgMeta, from::FromScript, into::IntoScript, type_dependencies::GetTypeDependencies,
};
use crate::{
ReflectReference, ScriptValue,
docgen::typed_through::{BoundPlaceholder, ThroughTypeInfo, TypedThrough},
error::InteropError,
};
macro_rules! impl_bound_reference {
($ty:ident, $placeholder:ident) => {
impl IntoScript for $ty {
fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> {
self.0.into_script(world)
}
}
impl FromScript for $ty {
type This<'w> = Self;
fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
ReflectReference::from_script(value, scope).map($ty)
}
}
impl TypedThrough for $ty {
fn through_type_info() -> ThroughTypeInfo {
ThroughTypeInfo::Bound(BoundPlaceholder::$placeholder)
}
}
impl ArgMeta for $ty {}
impl GetTypeDependencies for $ty {
type Underlying = ReflectReference;
fn register_type_dependencies(_registry: &mut TypeRegistry) {}
}
};
}
pub struct BoundValue(pub ReflectReference);
impl_bound_reference!(BoundValue, Value);
pub fn is_asset_type(registry: &TypeRegistry, type_id: TypeId) -> bool {
registry
.get_type_data::<bevy_asset::ReflectAsset>(type_id)
.is_some()
}
pub enum BoundFields {
Keyed(HashMap<String, ScriptValue>),
Positional(VecDeque<ScriptValue>),
}
impl BoundFields {
pub fn into_map(self, one_indexed: bool) -> HashMap<String, ScriptValue> {
match self {
BoundFields::Keyed(map) => map,
BoundFields::Positional(list) => list
.into_iter()
.enumerate()
.map(|(idx, value)| ((idx + one_indexed as usize).to_string(), value))
.collect(),
}
}
}
impl FromScript for BoundFields {
type This<'w> = Self;
fn from_script(value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
match value {
ScriptValue::Map(map) => Ok(BoundFields::Keyed(map)),
ScriptValue::List(list) => Ok(BoundFields::Positional(list)),
value => Err(InteropError::value_mismatch(
TypeId::of::<HashMap<String, ScriptValue>>(),
value,
)),
}
}
}
impl ArgMeta for BoundFields {}
impl TypedThrough for BoundFields {
fn through_type_info() -> ThroughTypeInfo {
ThroughTypeInfo::Bound(BoundPlaceholder::Fields)
}
}
impl GetTypeDependencies for BoundFields {
type Underlying = Self;
fn register_type_dependencies(_registry: &mut TypeRegistry) {}
}