import {ref, onMounted} from 'vue';
import {findTreeNode} from "@/utils/tree-helper";
import {injectLocal, provideLocal} from "@vueuse/core";
import {useCacheStore} from "@/hooks/useCacheStore";
import {cacheActions} from "@/hooks/defineCacheActions";

const key = Symbol('MAJOR_TREE_SERVICE')

export const useProvideMajorTreeService = () => {
    const {dispatchCache} = useCacheStore()
    const majorTree = ref([])
    const findNodeByCode = (code) => findTreeNode(majorTree.value, m => m.code == code)
    const findNode = (predicate) => findTreeNode(majorTree.value, predicate)

    onMounted(async () => majorTree.value = await dispatchCache(cacheActions.getMajorTree))

    const options = {
        majorTree,
        findNode,
        findNodeByCode
    }
    provideLocal(key, options)
    return options
}

export const useInjectMajorTreeService = () => {
    return injectLocal(key)
}