import { observe } from '@threlte/core';
import { commonApi, Pose } from '@viamrobotics/sdk';
import { createRobotQuery, useRobotClient } from '@viamrobotics/svelte-sdk';
import { untrack } from 'svelte';
import { RefetchRates } from '../components/overlay/RefreshRate.svelte';
import { useEnvironment } from './useEnvironment.svelte';
import { useFrames } from './useFrames.svelte';
import { useLogs } from './useLogs.svelte';
import { RefreshRates, useMachineSettings } from './useMachineSettings.svelte';
import { usePartID } from './usePartID.svelte';
import { useRefetchPoses } from './useRefetchPoses';
import { useResourceByName } from './useResourceByName.svelte';
const originFrameComponentTypes = new Set(['arm', 'gantry', 'gripper', 'base']);
export const usePose = (name, parent) => {
    const environment = useEnvironment();
    const logs = useLogs();
    const { refreshRates } = useMachineSettings();
    const partID = usePartID();
    const robotClient = useRobotClient(() => partID.current);
    const currentName = $derived(name());
    const currentParent = $derived(parent());
    const resourceByName = useResourceByName();
    const { addQueryToRefetch } = useRefetchPoses();
    const resource = $derived(currentName ? resourceByName.current[currentName] : undefined);
    const parentResource = $derived(currentParent ? resourceByName.current[currentParent] : undefined);
    const frames = useFrames();
    let pose = $state();
    const interval = $derived(refreshRates.get(RefreshRates.poses));
    const resolvedParent = $derived(originFrameComponentTypes.has(parentResource?.subtype ?? '') ? `${parent()}_origin` : parent());
    const resolvedName = $derived(originFrameComponentTypes.has(resource?.subtype ?? '') ? `${currentName}_origin` : currentName);
    const query = createRobotQuery(robotClient, 'getPose', () => [resolvedName, resolvedParent ?? 'world', []], () => ({
        enabled: interval !== RefetchRates.OFF && environment.current.viewerMode === 'monitor',
        refetchInterval: interval === RefetchRates.MANUAL ? false : interval,
    }));
    $effect(() => {
        if (environment.current.viewerMode === 'monitor') {
            pose = query.data?.pose;
        }
    });
    $effect(() => addQueryToRefetch(query));
    $effect(() => {
        if (interval === RefetchRates.FPS_30 || interval === RefetchRates.FPS_60) {
            return logs.add(`Fetching pose for ${currentName} every ${interval}ms...`);
        }
        if (query.isFetching) {
            logs.add(`Fetching pose for ${currentName}...`);
        }
        else if (query.error) {
            logs.add(`Error fetching pose for ${currentName}: ${query.error.message}`, 'error');
        }
    });
    observe.pre(() => [environment.current.viewerMode, frames.current], () => {
        if (environment.current.viewerMode === 'monitor') {
            untrack(() => query.refetch());
        }
    });
    return {
        get current() {
            return pose;
        },
    };
};
