aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/data/StopDataProvider.ts
blob: 76182c769fc059f7f8609cabc6cc18cea0d66b00 (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { APP_CONSTANTS } from "~/config/constants";

export interface Stop {
  stopId: string;
  stopCode?: string;
  name: string;
  latitude?: number;
  longitude?: number;
  lines: {
    line: string;
    colour: string;
    textColour: string;
  }[];
  favourite?: boolean;
  type?: "bus" | "coach" | "train" | "unknown";
}

interface CacheEntry {
  stop: Stop;
  timestamp: number;
}

const CACHE_KEY = `stops_cache_${APP_CONSTANTS.id}`;
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours

// In-memory cache for the current session
const memoryCache: Record<string, Stop> = {};

// Custom names loaded from localStorage per region
const customNamesByRegion: Record<string, Record<string, string>> = {};

// Helper to normalize ID
function normalizeId(id: number | string): string {
  const s = String(id);
  if (s.includes(":")) return s;
  return `vitrasa:${s}`;
}

function getPersistentCache(): Record<string, CacheEntry> {
  const raw = localStorage.getItem(CACHE_KEY);
  if (!raw) return {};
  try {
    return JSON.parse(raw);
  } catch {
    return {};
  }
}

function savePersistentCache(cache: Record<string, CacheEntry>) {
  localStorage.setItem(CACHE_KEY, JSON.stringify(cache));
}

async function fetchStopsByIds(ids: string[]): Promise<Record<string, Stop>> {
  if (ids.length === 0) return {};

  const normalizedIds = ids.map(normalizeId);
  const now = Date.now();
  const persistentCache = getPersistentCache();
  const result: Record<string, Stop> = {};
  const toFetch: string[] = [];

  for (const id of normalizedIds) {
    if (memoryCache[id]) {
      result[id] = memoryCache[id];
      continue;
    }

    const cached = persistentCache[id];
    if (cached && now - cached.timestamp < CACHE_DURATION) {
      memoryCache[id] = cached.stop;
      result[id] = cached.stop;
      continue;
    }

    toFetch.push(id);
  }

  if (toFetch.length > 0) {
    try {
      const response = await fetch(`/api/stops?ids=${toFetch.join(",")}`);
      if (!response.ok) throw new Error("Failed to fetch stops");

      const data = await response.json();
      for (const [id, stopData] of Object.entries(data)) {
        const stop: Stop = {
          stopId: (stopData as any).id,
          stopCode: (stopData as any).code,
          name: (stopData as any).name,
          lines: (stopData as any).routes.map((r: any) => ({
            line: r.shortName,
            colour: r.colour,
            textColour: r.textColour,
          })),
          type: (stopData as any).id.startsWith("renfe:")
            ? "train"
            : (stopData as any).id.startsWith("xunta:")
              ? "coach"
              : "bus",
        };

        memoryCache[id] = stop;
        result[id] = stop;
        persistentCache[id] = { stop, timestamp: now };
      }
      savePersistentCache(persistentCache);
    } catch (error) {
      console.error("Error fetching stops:", error);
    }
  }

  return result;
}

async function getStopById(stopId: string | number): Promise<Stop | undefined> {
  const id = normalizeId(stopId);
  const stops = await fetchStopsByIds([id]);
  const stop = stops[id];
  if (stop) {
    stop.favourite = isFavourite(id);
  }
  return stop;
}

function getDisplayName(stop: Stop): string {
  const custom = getCustomName(stop.stopId);
  return custom || stop.name;
}

function setCustomName(stopId: string | number, label: string) {
  const id = normalizeId(stopId);
  if (!customNamesByRegion[APP_CONSTANTS.id]) {
    const rawCustom = localStorage.getItem(
      `customStopNames_${APP_CONSTANTS.id}`
    );
    customNamesByRegion[APP_CONSTANTS.id] = rawCustom
      ? JSON.parse(rawCustom)
      : {};
  }
  customNamesByRegion[APP_CONSTANTS.id][id] = label;
  localStorage.setItem(
    `customStopNames_${APP_CONSTANTS.id}`,
    JSON.stringify(customNamesByRegion[APP_CONSTANTS.id])
  );
}

function removeCustomName(stopId: string | number) {
  const id = normalizeId(stopId);
  if (!customNamesByRegion[APP_CONSTANTS.id]) {
    const rawCustom = localStorage.getItem(
      `customStopNames_${APP_CONSTANTS.id}`
    );
    customNamesByRegion[APP_CONSTANTS.id] = rawCustom
      ? JSON.parse(rawCustom)
      : {};
  }
  if (customNamesByRegion[APP_CONSTANTS.id][id]) {
    delete customNamesByRegion[APP_CONSTANTS.id][id];
    localStorage.setItem(
      `customStopNames_${APP_CONSTANTS.id}`,
      JSON.stringify(customNamesByRegion[APP_CONSTANTS.id])
    );
  }
}

function getCustomName(stopId: string | number): string | undefined {
  const id = normalizeId(stopId);
  if (!customNamesByRegion[APP_CONSTANTS.id]) {
    const rawCustom = localStorage.getItem(
      `customStopNames_${APP_CONSTANTS.id}`
    );
    customNamesByRegion[APP_CONSTANTS.id] = rawCustom
      ? JSON.parse(rawCustom)
      : {};
  }
  return customNamesByRegion[APP_CONSTANTS.id][id];
}

function addFavourite(stopId: string | number) {
  const id = normalizeId(stopId);
  const rawFavouriteStops = localStorage.getItem(
    `favouriteStops_${APP_CONSTANTS.id}`
  );
  let favouriteStops: string[] = [];
  if (rawFavouriteStops) {
    favouriteStops = (JSON.parse(rawFavouriteStops) as (number | string)[]).map(
      normalizeId
    );
  }

  if (!favouriteStops.includes(id)) {
    favouriteStops.push(id);
    localStorage.setItem(
      `favouriteStops_${APP_CONSTANTS.id}`,
      JSON.stringify(favouriteStops)
    );
  }
}

function removeFavourite(stopId: string | number) {
  const id = normalizeId(stopId);
  const rawFavouriteStops = localStorage.getItem(
    `favouriteStops_${APP_CONSTANTS.id}`
  );
  let favouriteStops: string[] = [];
  if (rawFavouriteStops) {
    favouriteStops = (JSON.parse(rawFavouriteStops) as (number | string)[]).map(
      normalizeId
    );
  }

  const newFavouriteStops = favouriteStops.filter((sid) => sid !== id);
  localStorage.setItem(
    `favouriteStops_${APP_CONSTANTS.id}`,
    JSON.stringify(newFavouriteStops)
  );
}

function isFavourite(stopId: string | number): boolean {
  const id = normalizeId(stopId);
  const rawFavouriteStops = localStorage.getItem(
    `favouriteStops_${APP_CONSTANTS.id}`
  );
  if (rawFavouriteStops) {
    const favouriteStops = (
      JSON.parse(rawFavouriteStops) as (number | string)[]
    ).map(normalizeId);
    return favouriteStops.includes(id);
  }
  return false;
}

const RECENT_STOPS_LIMIT = 10;

function pushRecent(stopId: string | number) {
  const id = normalizeId(stopId);
  const rawRecentStops = localStorage.getItem(
    `recentStops_${APP_CONSTANTS.id}`
  );
  let recentStops: string[] = [];
  if (rawRecentStops) {
    recentStops = (JSON.parse(rawRecentStops) as (number | string)[]).map(
      normalizeId
    );
  }

  // Remove if already exists to move to front
  recentStops = recentStops.filter((sid) => sid !== id);
  recentStops.unshift(id);

  if (recentStops.length > RECENT_STOPS_LIMIT) {
    recentStops = recentStops.slice(0, RECENT_STOPS_LIMIT);
  }

  localStorage.setItem(
    `recentStops_${APP_CONSTANTS.id}`,
    JSON.stringify(recentStops)
  );
}

function getRecent(): string[] {
  const rawRecentStops = localStorage.getItem(
    `recentStops_${APP_CONSTANTS.id}`
  );
  if (rawRecentStops) {
    return (JSON.parse(rawRecentStops) as (number | string)[]).map(normalizeId);
  }
  return [];
}

function getFavouriteIds(): string[] {
  const rawFavouriteStops = localStorage.getItem(
    `favouriteStops_${APP_CONSTANTS.id}`
  );
  if (rawFavouriteStops) {
    return (JSON.parse(rawFavouriteStops) as (number | string)[]).map(
      normalizeId
    );
  }
  return [];
}

function getTileUrlTemplate(): string {
  return window.location.origin + "/api/tiles/stops/{z}/{x}/{y}";
}

export default {
  getStopById,
  fetchStopsByIds,
  getCustomName,
  getDisplayName,
  setCustomName,
  removeCustomName,
  addFavourite,
  removeFavourite,
  isFavourite,
  pushRecent,
  getRecent,
  getFavouriteIds,
  getTileUrlTemplate,
};