import React, { useEffect, useState } from "react";
import { AgentAccess } from "config";
import { useProjectId } from "./lib/state";

export function Agent({ agent }: { agent: AgentAccess }): React.ReactNode {
	return <AgentIframe agent={agent} />;
}

export function AgentIframe({ agent }: { agent: AgentAccess }): React.ReactNode {
	const projectId = useProjectId();
	const [ok, setOk] = useState<boolean>(false);
	useEffect(() => {
		let timeout: NodeJS.Timeout | null = null;
		const check = async () => {
			const resp = await fetch(`/api/project/${projectId}/agent/${agent.agentName}/status`);
			if (resp.ok) {
				const status = (await resp.json()).status;
				if (200 <= status && status < 300) {
					setOk(true);
					return;
				}
			}
			timeout = setTimeout(check, 500);
		};
		check();
		return () => {
			if (timeout != null) {
				clearTimeout(timeout);
			}
		};
	}, [agent.agentName, agent.address, setOk, projectId]);
	if (!ok) {
		return <div>Agent {agent.agentName} is loading...</div>;
	}
	return <iframe key={agent.name} src={`${agent.address}?m`} title={agent.agentName} className="w-full h-full" />;
}
