From 2656a9c1ed802f87d30530f6cea502a3238880de Mon Sep 17 00:00:00 2001
From: Ariel Costas Guerrero <94913521+arielcostas@users.noreply.github.com>
Date: Mon, 26 Aug 2024 00:12:23 +0200
Subject: Add simpleCSS, improve usability

---
 src/pages/Home.tsx | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 55 insertions(+), 3 deletions(-)

(limited to 'src/pages/Home.tsx')

diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx
index 79f1ec2..14d5d7a 100644
--- a/src/pages/Home.tsx
+++ b/src/pages/Home.tsx
@@ -1,3 +1,4 @@
+import { useNavigate } from "react-router-dom";
 import useSWR from "swr";
 
 interface Stop {
@@ -8,12 +9,50 @@ interface Stop {
 	lines: string[];
 }
 
+interface CachedStopList {
+	timetsamp: number;
+	data: Stop[];
+}
+
 export function Home() {
+	const navigate = useNavigate()
 	const { data, error, isLoading } = useSWR<Stop[]>('home', async () => {
+		const cachedData = localStorage.getItem('cachedStopList')
+		if (cachedData) {
+			const parsedData: CachedStopList = JSON.parse(cachedData)
+
+			// Cache for 12 hours
+			if (Date.now() - parsedData.timetsamp < 1000 * 60 * 60 * 12) {
+				console.log("parsed data: ", parsedData.data)
+				return parsedData.data
+			} else {
+				localStorage.removeItem('cachedStopList')
+			}
+		}
+
 		const response = await fetch('/api/ListStops')
-		return response.json()
+		const body = await response.json();
+
+		localStorage.setItem('cachedStopList', JSON.stringify({
+			timestamp: Date.now(),
+			data: body
+		}));
+		
+		return body;
 	});
 
+	const handleStopSearch = async (event: React.FormEvent) => {
+		event.preventDefault()
+
+		const stopId = (event.target as HTMLFormElement).stopId.value
+		const searchNumber = parseInt(stopId)
+		if (data?.find(stop => stop.stopId === searchNumber)) {
+			navigate(`/${searchNumber}`)
+		} else {
+			alert("Parada no encontrada")
+		}
+	}
+
 	if (isLoading) return <h1>Loading...</h1>
 	if (error) return <h1>Error</h1>
 
@@ -21,10 +60,23 @@ export function Home() {
 		<>
 			<h1>Home</h1>
 
+			<form action="none" onSubmit={handleStopSearch}>
+				<div>
+					<label htmlFor="stopId">
+						ID
+					</label>
+					<input type="number" placeholder="ID de parada" id="stopId" />
+				</div>
+
+				<button type="submit">Buscar</button>
+			</form>
+
 			<ul>
-				{data?.map((stop: Stop) => (
+				{data?.sort((a, b) => a.stopId - b.stopId).map((stop: Stop) => (
 					<li key={stop.stopId}>
-						{stop.name} - {stop.lines?.join(', ')}
+						<a href={`/${stop.stopId}`}>
+							({stop.stopId}) {stop.name} - {stop.lines?.join(', ')}
+						</a>
 					</li>
 				))}
 			</ul>
-- 
cgit v1.3

