-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvgPool.html
544 lines (470 loc) · 20.1 KB
/
vgPool.html
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vendée Globe Standings</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
tr:hover {
background-color: #f5f5f5;
}
.loading {
text-align: center;
padding: 20px;
}
.error {
color: red;
text-align: center;
padding: 20px;
}
.country-flag {
height: 20px;
vertical-align: middle;
margin-right: 10px;
}
.last-update {
text-align: right;
color: #666;
font-style: italic;
}
.highlighted {
background-color: #fff3e0;
}
.cache-status {
text-align: right;
color: #666;
font-style: italic;
margin-top: 20px;
margin-bottom: 20px;
font-size: 0.9em;
padding: 10px;
background-color: #f8f8f8;
border-radius: 4px;
}
.cache-status button {
margin-left: 10px;
padding: 4px 8px;
font-size: 0.9em;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
cursor: pointer;
}
.cache-status button:hover {
background-color: #f0f0f0;
}
/* Add responsive styles */
@media screen and (max-width: 768px) {
body {
padding: 15px;
}
table {
display: block;
overflow-x: auto;
white-space: nowrap;
width: 100%;
}
th, td {
white-space: nowrap;
text-align: left;
padding: 12px;
font-size: 0.95em;
}
tr {
display: table-row; /* Prevent tr wrapping */
line-height: 1.5;
}
.cache-status button {
display: block;
width: 100%;
margin-top: 10px;
}
.hide-mobile {
display: none;
}
}
@media screen and (max-width: 600px) {
.highlighted {
padding: 8px;
font-size: 0.9em;
}
}
</style>
</head>
<body>
<h1>Vendée Globe Standings</h1>
<div id="lastUpdate" class="last-update">
<span id="currentUpdate"></span>
<span id="nextUpdate"></span>
</div>
<div id="rankings">
<p class="loading">Loading rankings...</p>
</div>
<h2>Betting Results</h2>
<div id="bettingResults">
<p class="loading">Loading betting results...</p>
</div>
<hr style="margin-top: 30px;">
<div id="cacheStatus" class="cache-status"></div>
<script>
// Configuration
const USE_LOCAL_FILE = false; // Set to false to use API instead
const LOCAL_FILE = 'rankings.json';
const API_KEY = 'cm4vpqqd4000013s28hk9mbyg';
const API_URL = 'https://www.vendeeglobeapi.com/api/vgdata?apikey=' + API_KEY;
const UPDATE_RAW = ['03:00', '07:00', '11:00', '15:00', '19:00', '23:00'];
const UPDATE_TIMES = UPDATE_RAW.map(t => {
const [hour, minute] = t.split(':').map(Number);
return hour * 60 + minute;
});
function shouldFetchNewData(lastUpdateTime) {
if (!lastUpdateTime) return true;
// We fetch updates when they are *NEW*. New updates are available at the UPDATE_TIMES.
// If we fetch at 10:00, there is a new one at 11:00. At 10:30 there is no need to fetch.
// Ranking data contains a lastUpdate in French timezone (format 19h00)
const lastUpdateHour = parseInt(lastUpdateTime.split('h')[0]);
const lastUpdateMinute = parseInt(lastUpdateTime.split('h')[1]);
// Get current time in French timezone (UTC+1)
const now = new Date();
const minutesToFrance = now.getTimezoneOffset() + 60; // local offset + 1 hour for France
const frenchNow = new Date(now.getTime() + minutesToFrance * 60000); // convert minutes to milliseconds
// Debug logging of current time and French time
console.log('Current local time:', now.toLocaleString());
console.log('Current local time:', frenchNow.toLocaleString());
const currentHour = frenchNow.getHours();
const currentMinute = frenchNow.getMinutes();
const currentTimeInMinutes = currentHour * 60 + currentMinute;
console.log('Current time in France:', `${currentHour}h${currentMinute}`);
let lastScheduledUpdate = UPDATE_TIMES[UPDATE_TIMES.length - 1];
for (const time of UPDATE_TIMES) {
if (time <= currentTimeInMinutes) {
lastScheduledUpdate = time;
}
}
// Finally, if the last actual update is before the last scheduled update, we need new data.
return lastUpdateTime < lastScheduledUpdate;
}
// Modified cache management functions
function saveToCache(key, data) {
const cacheEntry = {
timestamp: new Date().getTime(),
data: data
};
console.log(`Saving to ${key} cache at:`, formatDateTime(cacheEntry.timestamp));
localStorage.setItem(key, JSON.stringify(cacheEntry));
}
function getFromCache(key) {
const cached = localStorage.getItem(key);
if (!cached) {
console.log(`No cached data found for ${key}`);
return null;
}
const entry = JSON.parse(cached);
// For rankings, check if new data should be available
if (key === 'rankings' && shouldFetchNewData(entry.data.latestdata.lastUpdate)) {
console.log('New race update should be available, invalidating cache');
localStorage.removeItem(key);
return null;
}
console.log(`Using valid ${key} cache from:`, formatDateTime(entry.timestamp));
return entry;
}
// Define selected skippers and their status
const selectedSkippers = new Set([
'Samantha Davies',
'Justine Mettraux',
'Clarisse Crémer',
'Pip Hare', // Abandoned
'Isabelle Joschke',
'Violette Dorange'
]);
// Define abandoned skippers in order of abandonment
const abandonedSkippers = [
'Pip Hare'
];
// Helper function to check if a skipper has abandoned
function isAbandonedSkipper(skipperName) {
return abandonedSkippers.includes(skipperName);
}
// Modified computeInversions function with abandoned skipper handling
function computeInversions(ranked_list, bet) {
let inversions = 0;
const n = ranked_list.length;
// Create complete ranking list including abandoned skippers at the end
const completeRankings = [...ranked_list, ...abandonedSkippers];
console.log("Computing inversions:");
console.log("Complete rankings (including abandoned):", completeRankings);
console.log("Bet:", bet);
for (let i = 0; i < completeRankings.length; i++) {
for (let j = i + 1; j < completeRankings.length; j++) {
const skipper1 = completeRankings[i];
const skipper2 = completeRankings[j];
const bet_pos1 = bet.indexOf(skipper1);
const bet_pos2 = bet.indexOf(skipper2);
if (bet_pos1 > bet_pos2) {
inversions += 1;
}
}
}
console.log("Total inversions:", inversions);
return inversions;
}
function formatDateTime(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString();
}
function updateCacheStatus(source, timestamp, lastUpdate) {
const cacheStatusDiv = document.getElementById('cacheStatus');
const age = Math.round((new Date().getTime() - timestamp) / 60000);
let statusHtml = `Data source: <strong>${source}</strong>`;
if (timestamp) {
statusHtml += ` (cached ${age} minutes ago at ${formatDateTime(timestamp)})`;
}
// Add next update time info
if (lastUpdate) {
const nextUpdate = getNextUpdateTime(lastUpdate);
statusHtml += `<br>Next race update expected at: ${nextUpdate} (French time)`;
}
statusHtml += `
<button onclick="clearCache()">
Clear Cache
</button>`;
cacheStatusDiv.innerHTML = statusHtml;
}
function getNextUpdateTime(lastUpdate) {
// Convert French time format (19h00) to hour
const currentHour = parseInt(lastUpdate.split('h')[0]);
// Find next update time
for (const updateTime of UPDATE_TIMES) {
// convert minutes to hours
const hour = Math.floor(updateTime / 60);
if (hour > currentHour) {
return `${hour}h00`;
}
}
// If no later time found, return first time next day
const firstUpdateHour = Math.floor(UPDATE_TIMES[0] / 60);
return `${firstUpdateHour}h00`;
}
function clearCache() {
console.log('Clearing cache...');
localStorage.clear();
location.reload();
}
async function fetchBettingResults(actualRankings) {
try {
let bets;
const cachedBets = getFromCache('bets');
if (cachedBets) {
console.log('Using cached betting data');
bets = cachedBets.data;
} else {
console.log('Fetching fresh betting data');
const response = await fetch('bets.json');
if (!response.ok) {
throw new Error('Error loading bets file');
}
bets = await response.json();
// Save the new data to cache
saveToCache('bets', bets);
}
// Get actual rankings order and add abandoned skippers at the end
const rankedSkippers = actualRankings.map(boat => boat.Skipper_Boat);
console.log("Active rankings order:", rankedSkippers);
// Process each bet and compute inversions
const processedBets = bets
// .filter(bet => bet.paid === 'Yes')
.map(bet => {
// Create ordered list of skippers based on bet
const betOrder = Array(6).fill(null);
for (const skipper of selectedSkippers) {
const position = parseInt(bet[skipper]) - 1;
betOrder[position] = skipper;
}
console.log("Processing bet:", bet.email);
console.log("Bet order:", betOrder);
const invCount = computeInversions(rankedSkippers, betOrder);
return {
email: bet.email,
inversions: invCount,
betAmount: bet.bet_amount,
betOrder: betOrder
};
})
.sort((a, b) => a.inversions - b.inversions);
// Create results table
const resultsDiv = document.getElementById('bettingResults');
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
thead.innerHTML = `
<tr>
<th>Email</th>
<th>Score</th>
<th class="hide-mobile">Bet</th>
<th class="hide-mobile">Prediction</th>
</tr>
`;
processedBets.forEach(bet => {
const row = document.createElement('tr');
row.innerHTML = `
<td data-label="Email">${bet.email.split('@')[0]}</td>
<td data-label="Score">${bet.inversions}</td>
<td data-label="Bet" class="hide-mobile">$${bet.betAmount}</td>
<td data-label="Prediction" class="hide-mobile">${bet.betOrder.join(' → ')}</td>
`;
tbody.appendChild(row);
});
table.appendChild(thead);
table.appendChild(tbody);
resultsDiv.innerHTML = '';
resultsDiv.appendChild(table);
} catch (error) {
console.error("Error in fetchBettingResults:", error);
document.getElementById('bettingResults').innerHTML = `
<p class="error">Error loading betting results: ${error.message}</p>
`;
}
}
async function fetchRankings() {
const rankingsDiv = document.getElementById('rankings');
const lastUpdateDiv = document.getElementById('lastUpdate');
try {
let data;
let dataSource = 'Live API';
let cacheTimestamp = null;
const cachedData = getFromCache('rankings');
if (cachedData) {
console.log('Using cached rankings data from:', formatDateTime(cachedData.timestamp));
data = cachedData.data;
dataSource = 'Cache';
cacheTimestamp = cachedData.timestamp;
} else {
console.log('Fetching fresh rankings data');
if (USE_LOCAL_FILE) {
const response = await fetch(LOCAL_FILE);
if (!response.ok) {
throw new Error('Error loading local file');
}
data = await response.json();
dataSource = 'Local File';
} else {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error('Network response was not ok');
}
data = await response.json();
}
// Save the new data to cache
saveToCache('rankings', data);
}
// Update cache status with next update time
updateCacheStatus(dataSource, cacheTimestamp, data.latestdata.lastUpdate);
// Filter only selected skippers
const raceData = data.latestdata.data.filter(boat =>
selectedSkippers.has(boat.Skipper_Boat)
);
lastUpdateDiv.innerHTML = `
<span>Rankings Last Updated by Vendée Globe: ${data.latestdata.lastUpdate} (French time)</span>
<span style="margin-left: 20px;">Next Update Expected: ${getNextUpdateTime(data.latestdata.lastUpdate)}</span>
`;
// Create table
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
thead.innerHTML = `
<tr>
<th>Rank</th>
<th>Skipper</th>
<th>DTF</th>
<th class="hide-mobile">DTL</th>
<th class="hide-mobile">Speed</th>
<th class="hide-mobile">24h Dist</th>
</tr>
`;
// Sort by rank
raceData.sort((a, b) => Number(a.Rank) - Number(b.Rank));
const countryToFlag = {
'FR': '🇫🇷',
'GB': '🇬🇧',
'CHE': '🇨🇭', // Switzerland
'CN': '🇨🇭', // Switzerland *HACK* because of bug
'ESP': '🇪🇸',
'ITA': '🇮🇹',
'DEU': '🇩🇪', // Germany
'USA': '🇺🇸',
'NZL': '🇳🇿',
'AUS': '🇦🇺',
'NED': '🇳🇱', // Netherlands
'POR': '🇵🇹',
'BEL': '🇧🇪',
'IRL': '🇮🇪',
'CAN': '🇨🇦',
};
// Add active skippers
raceData.forEach(boat => {
const row = document.createElement('tr');
const flag = countryToFlag[boat.Country] || '🏳️';
const skipperName = boat.Skipper_Boat.split(' - ')[0];
row.innerHTML = `
<td>${boat.Rank}</td>
<td><span class="hide-mobile">${flag}</span>${skipperName}</td>
<td>${boat.DTF}</td>
<td class="hide-mobile">${boat.DTL}</td>
<td class="hide-mobile">${boat.Speed_24h}</td>
<td class="hide-mobile">${boat.Distance_24h}</td>
`;
tbody.appendChild(row);
});
// Add abandoned skippers
abandonedSkippers.forEach(skipperName => {
const row = document.createElement('tr');
row.style.backgroundColor = '#ffebee'; // Light red background
row.innerHTML = `
<td>-</td>
<td>${skipperName}</td>
<td colspan="4" style="color: #d32f2f;">Abandoned</td>
`;
tbody.appendChild(row);
});
table.appendChild(thead);
table.appendChild(tbody);
rankingsDiv.innerHTML = '';
rankingsDiv.appendChild(table);
// After successfully loading rankings, fetch betting results
await fetchBettingResults(raceData);
} catch (error) {
console.error('Error in fetchRankings:', error);
rankingsDiv.innerHTML = `
<p class="error">Error loading rankings: ${error.message}</p>
`;
}
}
// Fetch rankings when page loads
fetchRankings();
// Only set up interval refresh if using API
if (!USE_LOCAL_FILE) {
setInterval(fetchRankings, 5 * 60 * 1000);
}
</script>
</body>
</html>