import { invoke } from '@tauri-apps/api/core';
import { useCleanup, useI18n, useMessage } from 'hooks';
import { useAtom, useSetAtom } from 'jotai';
import { toast } from 'sonner';
import {
dynamicVisibleAtom,
loadingAtom,
modelPathAtom,
fsgVisibleAtom,
translateAtom,
useSelectionHistory,
useZoom,
currentGraphAtom,
graphTreeAtom,
fsgPanelVisibleAtom,
dynamicNodesAtom,
showThumbnailAtom,
graphDataAtom,
expandGraphDataAtom,
} from 'stores';
import { useRecentProjectStorage } from 'stores/useRecentProjectStorage';
import { ModelType } from 'types/enum';
type LayoutNewPath = (path: string | null) => Promise<void>
export const useNewPathForLayout = (): LayoutNewPath => {
const [modelPath, setModelPath] = useAtom(modelPathAtom);
const history = useSelectionHistory();
const setCurrentGraph = useSetAtom(currentGraphAtom);
const setGraphTree = useSetAtom(graphTreeAtom);
const setGraphData = useSetAtom(graphDataAtom);
const setDynamicVisible = useSetAtom(dynamicVisibleAtom);
const setDynamicNodes = useSetAtom(dynamicNodesAtom);
const setFsgPanelVisible = useSetAtom(fsgPanelVisibleAtom);
const setFsgsVisible = useSetAtom(fsgVisibleAtom);
const setShowThumbnail = useSetAtom(showThumbnailAtom);
const setTranslate = useSetAtom(translateAtom);
const setExpandGraphData = useSetAtom(expandGraphDataAtom);
const [, , , resetZoom] = useZoom();
const setLoading = useSetAtom(loadingAtom);
const { recentProjCacheAdd } = useRecentProjectStorage();
const t = useI18n();
const { error } = useMessage();
const cleanup = useCleanup();
return async (path: string | null) => {
if (!path || path === modelPath) { return; }
setLoading(true);
const start = performance.now();
try {
await invoke<LayoutRet>('check_path', { path });
setFsgPanelVisible(false);
history.clear();
setCurrentGraph({ children: [], name: '', paths: [], model_type: ModelType.Unsupported });
setGraphData({});
setDynamicVisible(false);
setDynamicNodes(null);
setFsgsVisible(false);
setShowThumbnail(false);
setExpandGraphData({});
} catch (err) {
error(err as RequestError);
setLoading(false);
return;
}
try {
const res = await invoke<LayoutRet>('layout_bin', { path });
if (res !== null) {
setModelPath(path);
setCurrentGraph(res);
setGraphTree(res);
recentProjCacheAdd(path);
resetZoom();
setTranslate({ x: 0, y: 0 });
}
} catch (err) {
error(err as RequestError);
cleanup();
setLoading(false);
return;
}
toast.success(t('parseAndTransfer', { time: Math.round(performance.now() - start) }), {
richColors: true,
closeButton: true
});
};
};