aboutsummaryrefslogtreecommitdiff
path: root/src/pages/Stop.tsx
blob: a5effc116d6f919fb16c03ca7e04581b11f903d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { Link, useParams } from "react-router-dom";
import useSWR from "swr";

interface StopDetails {
	stop: {
		id: number;
		name: string;
		latitude: number;
		longitude: number;
	}
	estimates: [{
		line: string;
		route: string;
		minutes: number;
		meters: number;
	}]
}

export function Stop(): JSX.Element {
	const params = useParams();

	const { data, error, isLoading } = useSWR<StopDetails>(`stop-${params.stopId}`, async () => {
		let response;

		try {
			response = await fetch(`/api/GetStopEstimates?id=${params.stopId}`)
			return response.json()
		} catch (error) {
			console.error(error)
			throw new Error(`Failed to fetch data, status ${response!.status}, body: ${await response!.text()}`)
		}
	});

	const absoluteArrivalTime = (minutes: number) => {
		const now = new Date()
		const arrival = new Date(now.getTime() + minutes * 60000)
		return Intl.DateTimeFormat(navigator.language, {
			hour: '2-digit',
			minute: '2-digit'
		}).format(arrival)
	}

	if (isLoading) return <h1>Loading...</h1>
	if (error) return <h1>Error: {JSON.stringify(error)}</h1>
	if (data === undefined) return <h1>No data</h1>

	return (
		<>
			<div>
				<h1>{data?.stop.name} ({data?.stop.id})</h1>
			</div>

			<Link to="/">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					strokeWidth="2"
					strokeLinecap="round"
					strokeLinejoin="round"
					style={{marginInlineEnd: '0.5em', width: '1em', height: '1em'}}
				>
					<path d="M19 12H5M12 19l-7-7 7-7" />
				</svg>
				Volver al listado de paradas
			</Link>

			<table>
				<caption>Estimaciones de llegadas</caption>

				<thead>
					<tr>
						<th>Línea</th>
						<th>Ruta</th>
						<th>Minutos</th>
						<th>Metros</th>
					</tr>
				</thead>

				<tbody>
					{data.estimates
						.sort((a, b) => a.minutes - b.minutes)
						.map((estimate, idx) => (
							<tr key={idx}>
								<td>{estimate.line}</td>
								<td>{estimate.route}</td>
								<td>
									{estimate.minutes} ({absoluteArrivalTime(estimate.minutes)})
								</td>
								<td>
									{estimate.meters > -1
										? `${estimate.meters} metros`
										: "No disponible"
									}
								</td>
							</tr>
						))}
				</tbody>
			</table>

			<p>
				<Link to="/">Volver al inicio</Link>
			</p>
		</>
	)
}