import { get } from './utils';
import type { Node, FullLinkApi } from '../routes/flow/types';

function createStatusStore() {
	let nodes: Node[] = $state([]);
	let links: FullLinkApi[] = $state([]);

	let nodesR: Record<string, Node> = $state({});
	let dirLinks: Record<string, Node[]> = $state({});

	let request = false;

	return {
		/**
		 * @throws {Error}
		 **/
		async load(clear = false) {
			if (!clear && nodes.length !== 0) {
				return;
			}
			if (request) return;

			request = true;

			try {
				nodes = await get('user/status/node');
				links = await get('user/status/link');
			} catch (e) {
				request = false;
				throw e;
			}

			dirLinks = {};
			nodesR = {};

			nodes.sort((a, b) => {
				if (a.y !== b.y) return a.y - b.y;
				return b.x - a.x;
			});

			for (const node of nodes) {
				nodesR[node.id] = node;
			}

			const nodesId: string[] = [null as any, ...Object.keys(nodesR)];

			nodesR[null as any] = {
				icon: 'plus',
				id: null as any,
				name: 'Created',
				x: -4,
				y: 10,
				width: 8,
				height: 4
			} as any;

			nodesR['null'] = {
				icon: 'plus',
				id: null as any,
				name: 'Created',
				x: -4,
				y: 10,
				width: 8,
				height: 4
			} as any;

			for (const nodeId of nodesId) {
				const targets = [];
				for (const link of links) {
					if (link.source_node === nodeId) {
						targets.push(nodesR[link.target_node as any]);
					}
				}
				dirLinks[nodeId] = targets;
			}

			request = false;
		},

		get nodes() {
			return nodes;
		},

		get nodesR() {
			return nodesR;
		},

		get dirLinks() {
			return dirLinks;
		}
	};
}

export const statusStore = createStatusStore();
