import { createResource, For, ParentComponent, useContext } from 'solid-js';

import { Stop } from '../types';
import { BusinessDataContext, BusinessDataStore } from "../businessData";
import { renderLinePicto, ScrollingText } from '../utils';

export const StopPopup: ParentComponent<{ stop: Stop, show: boolean }> = (props) => {
	const businessDataStore: BusinessDataStore | undefined = useContext(BusinessDataContext);
	if (businessDataStore === undefined)
		return <div />;

	const { getLine, getStopDestinations } = businessDataStore;

	let popupDiv: HTMLDivElement | undefined = undefined;

	const getDestinations = async (stop: Stop): Promise<{ lineId: string, destinations: string[] }[]> => {
		let ret = [];

		if (stop !== undefined) {
			const result = await getStopDestinations(stop.id);
			for (const [lineId, destinations] of Object.entries(result)) {
				const line = await getLine(lineId);
				const linePicto = renderLinePicto(line);
				ret.push({ lineId: linePicto, destinations: destinations });
			}
		}

		return ret;
	}
	const [destinations] = createResource(() => props.stop, getDestinations);

	return (
		<div ref={popupDiv} classList={{ "popup": true, "displayed": props.show }}>
			<div class="header">{props.stop?.name}</div>
			<div class="body">
				<For each={destinations()}>
					{(dst) => {
						return <div class='line'>
							{dst.lineId}
							<div class="name">
								<ScrollingText height={10} width={130} content={dst.destinations.join('/')} />
							</div>
						</div>;
					}}
				</For>
			</div>
		</div >
	);
}
