<script lang="ts">
	import { T } from '@threlte/core';
	import { TransformControls, interactivity } from '@threlte/extras';
	import type { Object3D } from 'three';
	import type { Snippet } from 'svelte';
	import type IUrdfJoint from './robot/URDF/interfaces/IUrdfJoint';
	import { updateOrigin } from './robot/URDF/utils/UrdfParser';
	import type { IUrdfVisual } from './robot/URDF/interfaces/IUrdfVisual';
	import type { TransformControlsMode } from 'three/examples/jsm/Addons.js';

	interface Props {
		origin: IUrdfJoint | IUrdfVisual;
		children?: Snippet; // renderable
		selected?: boolean;
		translationSnap?: number;
		scaleSnap?: number;
		rotationSnap?: number;
		tool?: TransformControlsMode;
		enableEdit?: boolean;
	}

	let {
		origin,
		children,
		selected = false,
		translationSnap = 0.1,
		scaleSnap = 0.1,
		rotationSnap = 0.1,
		tool = 'translate',
		enableEdit = true
	}: Props = $props();

	const updateData = (obj: Object3D) => {
		origin.origin_xyz = obj.position.toArray();
		origin.origin_rpy = [obj.rotation.x, obj.rotation.y, obj.rotation.z];
		updateOrigin(origin);
	};

	const onobjectChange = (event: any) => {
		if (!event.target) {
			return;
		}
		const obj = event.target.object;
		updateData(obj);
	};

	interactivity();
</script>

{#if selected && enableEdit}
	<TransformControls
		{translationSnap}
		{scaleSnap}
		rotationSnap={Math.PI / rotationSnap}
		position={origin.origin_xyz}
		rotation={origin.origin_rpy}
		mode={tool}
		{onobjectChange}
	>
		{@render children?.()}
	</TransformControls>
{:else}
	<T.Group position={origin.origin_xyz} rotation={origin.origin_rpy}>
		{@render children?.()}
	</T.Group>
{/if}

<!-- From https://github.com/brean/urdf-viewer -->
