<script lang="ts">
	import { goto } from '$app/navigation';
	import { notificationStore } from 'src/lib/NotificationsStore.svelte';
	import { post, showMessage } from 'src/lib/requests.svelte';
	import { userStore } from 'src/routes/UserStore.svelte';
	import { onMount } from 'svelte';
	import * as d3 from 'd3';

	import type { Base } from './types';
	import CardInfo from './CardInfo.svelte';

	let width = $state(0);
	let height = $state(0);

	function drag(simulation: d3.Simulation<d3.HierarchyNode<Base>, undefined>) {
		function dragstarted(event: any, d: any) {
			if (!event.active) simulation.alphaTarget(0.3).restart();
			d.fx = d.x;
			d.fy = d.y;
			selected = d.data;
		}

		function dragged(event: any, d: any) {
			d.fx = event.x;
			d.fy = event.y;
		}

		function dragended(event: any, d: any) {
			if (!event.active) simulation.alphaTarget(0);
			d.fx = null;
			d.fy = null;
		}

		return d3.drag().on('start', dragstarted).on('drag', dragged).on('end', dragended);
	}

	let graph: HTMLDivElement;

	let selected: Base | undefined = $state();

	async function getData() {
		const dataObj: Base = {
			name: 'API',
			type: 'api',
			children: []
		};

		if (!dataObj.children) throw new Error();

		const localRunners: Base[] = [];
		const remotePairs: Record<string, Base[]> = {};

		try {
			let data = await post('tasks/runner/info', {});

			if (Object.keys(data.localRunners).length > 0) {
				for (const objId of Object.keys(data.localRunners)) {
					localRunners.push({ name: objId, type: 'local_runner', task: data.localRunners[objId] });
				}

				dataObj.children.push({
					name: 'local runners',
					type: 'runner_group',
					children: localRunners
				});
			}

			if (Object.keys(data.remoteRunners).length > 0) {
				for (const objId of Object.keys(data.remoteRunners)) {
					let obj = data.remoteRunners[objId];
					if (remotePairs[obj.runner_info.user_id as string]) {
						remotePairs[obj.runner_info.user_id as string].push({
							name: objId,
							type: 'runner',
							task: obj.task,
							parent: data.remoteRunners[objId].runner_info.user_id
						});
					} else {
						remotePairs[data.remoteRunners[objId].runner_info.user_id] = [
							{
								name: objId,
								type: 'runner',
								task: obj.task,
								parent: data.remoteRunners[objId].runner_info.user_id
							}
						];
					}
				}
			}

			dataObj.children.push({
				name: 'remote runners',
				type: 'runner_group',
				task: undefined,
				children: Object.keys(remotePairs).map(
					(name) =>
						({
							name,
							type: 'user_group',
							task: undefined,
							children: remotePairs[name]
						}) as Base
				)
			});
		} catch (ex) {
			showMessage(ex, notificationStore, 'Failed to get Runner information');
			return;
		}

		const root = d3.hierarchy(dataObj);
		const links = root.links();
		const nodes = root.descendants();
		console.log(root, links, nodes);

		const simulation = d3
			.forceSimulation(nodes)
			.force(
				'link',
				d3
					.forceLink(links)
					.id((d: any) => d.id)
					.distance((d: any) => {
						let data = d.source.data as Base;
						switch (data.type) {
							case 'api':
								return 150;
							case 'runner_group':
								return 90;
							case 'user_group':
								return 80;
							case 'runner':
							case 'local_runner':
								return 20;
							default:
								throw new Error();
						}
					})
					.strength(1)
			)
			.force('charge', d3.forceManyBody().strength(-1000))
			.force('x', d3.forceX())
			.force('y', d3.forceY());

		const svg = d3
			.create('svg')
			.attr('width', width)
			.attr('height', height - 62)
			.attr('viewBox', [-width / 2, -height / 2, width, height])
			.attr('style', 'max-width: 100%; height: auto;');
		// Append links.
		const link = svg
			.append('g')
			.attr('stroke', '#999')
			.attr('stroke-opacity', 0.6)
			.selectAll('line')
			.data(links)
			.join('line');

		const database_svg = `
			<svg xmlns="http://www.w3.org/2000/svg" stroke-width="0.2" width="32" height="32" fill="currentColor" class="bi bi-database" viewBox="0 0 32 32">
			  <path transform="scale(2)" d="M4.318 2.687C5.234 2.271 6.536 2 8 2s2.766.27 3.682.687C12.644 3.125 13 3.627 13 4c0 .374-.356.875-1.318 1.313C10.766 5.729 9.464 6 8 6s-2.766-.27-3.682-.687C3.356 4.875 3 4.373 3 4c0-.374.356-.875 1.318-1.313M13 5.698V7c0 .374-.356.875-1.318 1.313C10.766 8.729 9.464 9 8 9s-2.766-.27-3.682-.687C3.356 7.875 3 7.373 3 7V5.698c.271.202.58.378.904.525C4.978 6.711 6.427 7 8 7s3.022-.289 4.096-.777A5 5 0 0 0 13 5.698M14 4c0-1.007-.875-1.755-1.904-2.223C11.022 1.289 9.573 1 8 1s-3.022.289-4.096.777C2.875 2.245 2 2.993 2 4v9c0 1.007.875 1.755 1.904 2.223C4.978 15.71 6.427 16 8 16s3.022-.289 4.096-.777C13.125 14.755 14 14.007 14 13zm-1 4.698V10c0 .374-.356.875-1.318 1.313C10.766 11.729 9.464 12 8 12s-2.766-.27-3.682-.687C3.356 10.875 3 10.373 3 10V8.698c.271.202.58.378.904.525C4.978 9.71 6.427 10 8 10s3.022-.289 4.096-.777A5 5 0 0 0 13 8.698m0 3V13c0 .374-.356.875-1.318 1.313C10.766 14.729 9.464 15 8 15s-2.766-.27-3.682-.687C3.356 13.875 3 13.373 3 13v-1.302c.271.202.58.378.904.525C4.978 12.71 6.427 13 8 13s3.022-.289 4.096-.777c.324-.147.633-.323.904-.525"/>
			</svg>
		`;

		const cpu_svg = `
			<svg stroke="white" fill="white" xmlns="http://www.w3.org/2000/svg" stroke-width="0.2" width="32" height="32" fill="currentColor" class="bi bi-cpu-fill" viewBox="0 0 32 32">
				<path transform="scale(2)" d="M6.5 6a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5z"/>
				<path transform="scale(2)" d="M5.5.5a.5.5 0 0 0-1 0V2A2.5 2.5 0 0 0 2 4.5H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2v1H.5a.5.5 0 0 0 0 1H2A2.5 2.5 0 0 0 4.5 14v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14h1v1.5a.5.5 0 0 0 1 0V14a2.5 2.5 0 0 0 2.5-2.5h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14v-1h1.5a.5.5 0 0 0 0-1H14A2.5 2.5 0 0 0 11.5 2V.5a.5.5 0 0 0-1 0V2h-1V.5a.5.5 0 0 0-1 0V2h-1V.5a.5.5 0 0 0-1 0V2h-1zm1 4.5h3A1.5 1.5 0 0 1 11 6.5v3A1.5 1.5 0 0 1 9.5 11h-3A1.5 1.5 0 0 1 5 9.5v-3A1.5 1.5 0 0 1 6.5 5"/>
			</svg>
		`;

		const user_svg = `
			<svg fill="white" stroke="white" xmlns="http://www.w3.org/2000/svg" stroke-width="0.2" width="32" height="32" fill="currentColor" class="bi bi-person-fill" viewBox="0 0 32 32">
			  <path transform="scale(2)" d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/>
			</svg>
		`;

		const inbox_fill = `
			<svg fill="white" stroke="white" xmlns="http://www.w3.org/2000/svg" stroke-width="0.2" width="32" height="32" fill="currentColor" class="bi bi-inbox-fill" viewBox="0 0 32 32">
	  			<path transform="scale(2)" d="M4.98 4a.5.5 0 0 0-.39.188L1.54 8H6a.5.5 0 0 1 .5.5 1.5 1.5 0 1 0 3 0A.5.5 0 0 1 10 8h4.46l-3.05-3.812A.5.5 0 0 0 11.02 4zm-1.17-.437A1.5 1.5 0 0 1 4.98 3h6.04a1.5 1.5 0 0 1 1.17.563l3.7 4.625a.5.5 0 0 1 .106.374l-.39 3.124A1.5 1.5 0 0 1 14.117 13H1.883a1.5 1.5 0 0 1-1.489-1.314l-.39-3.124a.5.5 0 0 1 .106-.374z"/>
			</svg>
		`;

		const node = svg
			.append('g')
			.attr('fill', '#fff')
			.attr('stroke', '#000')
			.attr('stroke-width', 1.5)
			.selectAll('g')
			.data(nodes)
			.join('g')
			.attr('style', 'cursor: pointer;')
			.call(drag(simulation) as any)
			.on('click', (e) => {
				console.log('test');
				function findData(obj: HTMLElement) {
					if ((obj as any).__data__) {
						return (obj as any).__data__;
					}
					if (!obj.parentElement) {
						throw new Error();
					}
					return findData(obj.parentElement);
				}
				let obj = findData(e.srcElement);
				console.log(obj);
				selected = obj.data;
			});

		node
			.append('circle')
			.attr('fill', (d: any) => {
				let data = d.data as Base;
				switch (data.type) {
					case 'api':
						return '#caf0f8';
					case 'runner_group':
						return '#00b4d8';
					case 'user_group':
						return '#0000ff';
					case 'runner':
					case 'local_runner':
						return '#03045e';
					default:
						throw new Error();
				}
			})
			.attr('stroke', (d: any) => {
				let data = d.data as Base;
				switch (data.type) {
					case 'api':
					case 'user_group':
					case 'runner_group':
						return '#fff';
					case 'runner':
					case 'local_runner':
						// TODO make this relient on the stauts
						return '#000';
					default:
						throw new Error();
				}
			})
			.attr('r', (d: any) => {
				let data = d.data as Base;
				switch (data.type) {
					case 'api':
						return 30;
					case 'runner_group':
						return 20;
					case 'user_group':
						return 25;
					case 'runner':
					case 'local_runner':
						return 30;
					default:
						throw new Error();
				}
			})
			.append('title')
			.text((d: any) => d.data.name);

		node
			.filter((d) => {
				return ['api', 'local_runner', 'runner', 'user_group', 'runner_group'].includes(
					d.data.type
				);
			})
			.append('g')
			.html((d) => {
				switch (d.data.type) {
					case 'api':
						return database_svg;
					case 'user_group':
						return user_svg;
					case 'runner_group':
						return inbox_fill;
					case 'local_runner':
					case 'runner':
						return cpu_svg;
					default:
						throw new Error();
				}
			});

		simulation.on('tick', () => {
			link
				.attr('x1', (d: any) => d.source.x)
				.attr('y1', (d: any) => d.source.y)
				.attr('x2', (d: any) => d.target.x)
				.attr('y2', (d: any) => d.target.y);

			node
				.select('circle')
				.attr('cx', (d: any) => d.x)
				.attr('cy', (d: any) => d.y);
			node
				.select('svg')
				.attr('x', (d: any) => d.x - 16)
				.attr('y', (d: any) => d.y - 16);
		});

		//invalidation.then(() => simulation.stop());

		graph.appendChild(svg.node() as any);
	}

	$effect(() => {
		console.log(selected);
	});

	onMount(() => {
		// Check if logged in and admin
		if (!userStore.user || userStore.user.user_type != 2) {
			goto('/');
			return;
		}
		getData();
	});
</script>

<svelte:window bind:innerWidth={width} bind:innerHeight={height} />
<svelte:head>
	<title>Runners</title>
</svelte:head>

<div class="graph-container">
	<div class="graph" bind:this={graph}></div>
	{#if selected}
		<div class="selected">
			<CardInfo item={selected} />
		</div>
	{/if}
</div>

<style lang="css">
	.graph-container {
		position: relative;
		.selected {
			position: absolute;
			right: 40px;
			top: 40px;
			width: 20%;
			height: auto;
			padding: 20px;
			background: white;
			border-radius: 20px;
			box-shadow: 1px 1px 8px 2px #22222244;
		}
	}
</style>
