import {LocalTestable, Testable, TestableInterface} from "./Testable";
import {TestableData, useNodesStore} from "./store";
import {Testables} from "./testables";

export const useTestable = <Options extends object = {}>(id: TestableData['id'] | TestableData<Options>): TestableInterface<Options> | undefined => {
    const testables: { current: Testables | undefined } = {
        current: undefined
    }

    let useLocalData = typeof id === 'object';

    useNodesStore(store => {
        const _testables = new Testables(store)

        testables.current = _testables

        // this will trigger a re-render when the testable data changes
        return useLocalData ? id.id : _testables.getNode(id as string)
    })

    if (useLocalData) {
        return new LocalTestable<Options>(id as TestableData<Options>)
    }

    if (!testables.current) {
        console.error('useTestable: testable not found', id);
        return;
    }

    return new Testable<Options>(testables.current, id as string);
}