aboutsummaryrefslogtreecommitdiff
path: root/src/pages/Estimates.tsx
blob: 900ffc5f0989c7afd541d298d891117b1d668550 (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
import { JSX, useEffect, useState } from "react";
import { useParams } from "react-router";
import { StopDataProvider } from "../data/StopDataProvider";
import { Star } from 'lucide-react';
import "../styles/Estimates.css";
import { RegularTable } from "../components/RegularTable";
import { useApp } from "../AppContext";
import { GroupedTable } from "../components/GroupedTable";

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

const sdp = new StopDataProvider();

const loadData = async (stopId: string) => {
	const resp = await fetch(`/api/GetStopEstimates?id=${stopId}`);
	return await resp.json();
};

export function Estimates(): JSX.Element {
	const [data, setData] = useState<StopDetails | null>(null);
	const [dataDate, setDataDate] = useState<Date | null>(null);
	const [favourited, setFavourited] = useState(false);
	const params = useParams();
	const { tableStyle } = useApp();

	useEffect(() => {
		loadData(params.stopId!)
			.then((body: StopDetails) => {
				setData(body);
				setDataDate(new Date());
			})


		sdp.pushRecent(parseInt(params.stopId ?? ""));

		setFavourited(
			sdp.isFavourite(parseInt(params.stopId ?? ""))
		);
	}, [params.stopId]);


	const toggleFavourite = () => {
		if (favourited) {
			sdp.removeFavourite(parseInt(params.stopId ?? ""));
			setFavourited(false);
		} else {
			sdp.addFavourite(parseInt(params.stopId ?? ""));
			setFavourited(true);
		}
	}

	if (data === null) return <h1 className="page-title">Cargando datos en tiempo real...</h1>

	return (
		<div className="page-container">
			<div className="estimates-header">
				<h1 className="page-title">
					<Star className={`star-icon ${favourited ? 'active' : ''}`} onClick={toggleFavourite} />
					{data?.stop.name} <span className="estimates-stop-id">({data?.stop.id})</span>
				</h1>
			</div>

			<div className="table-responsive">
				{tableStyle === 'grouped' ?
					<GroupedTable data={data} dataDate={dataDate} /> :
					<RegularTable data={data} dataDate={dataDate} />}
			</div>
		</div>
	)
}