From 32f52fe549c73e059585721af8fe20ed19489b9e Mon Sep 17 00:00:00 2001
From: Dan Cojocaru <dancojocaru2010@hotmail.com>
Date: Fri, 18 Nov 2022 01:52:43 +0100
Subject: [PATCH] Fix refresh button on view station page

---
 sw.js            |  2 +-
 view-station.css |  4 ++++
 view-station.js  | 34 +++++++++++++++++++++++++++++++---
 3 files changed, 36 insertions(+), 4 deletions(-)

diff --git a/sw.js b/sw.js
index 7cdb6f1..43b2484 100755
--- a/sw.js
+++ b/sw.js
@@ -1,4 +1,4 @@
-const VERSION = 'v15'
+const VERSION = 'v16'
 const API_ORIGIN = 'https://scraper.infotren.dcdev.ro/'
 const API_TRAINS = `${API_ORIGIN}v3/trains`
 const API_STATIONS = `${API_ORIGIN}v3/stations`
diff --git a/view-station.css b/view-station.css
index 0bc7d83..073b927 100644
--- a/view-station.css
+++ b/view-station.css
@@ -10,6 +10,10 @@
 	color: red !important;
 }
 
+.rsk {
+	cursor: pointer;
+}
+
 #-date {
 	display: flex;
 	justify-content: space-between;
diff --git a/view-station.js b/view-station.js
index 2823abc..ff7720b 100644
--- a/view-station.js
+++ b/view-station.js
@@ -114,14 +114,25 @@ function refresh() {
 			reschedule(10000)
 			return
 		}
-		return response.json()
+		var cacheDate = response.headers.get('SW-Cached-At')
+		return response.json().then(function (data) {
+			data['$cacheDate'] = cacheDate
+			return data
+		})
 	}).then(function (response) {
 		if (!response) {
 			return
 		}
+		var cacheDate = response['$cacheDate']
+		if (cacheDate) {
+			cacheDate = new Date(cacheDate)
+		}
+		var success = !cacheDate
 		stationData = response
 		onStationData(response)
-		reschedule()
+		// Check in 1 seconds if network error
+		reschedule(success ? undefined : 1000)
+		return success
 	}).catch(function (e) {
 		// Check in 1 second if network error
 		reschedule(1000)
@@ -136,7 +147,24 @@ window.addEventListener('unload', function (e) {
 })
 
 function rsk() {
-	refresh()
+	function changeRskText(newText) {
+		document.querySelectorAll('.rsk').forEach(function (elem) {
+			elem.textContent = newText
+		})
+	}
+
+	changeRskText('Refreshing...')
+	refresh().catch(function () { return false}).then(function (success) {
+		if (!success) {
+			changeRskText('Refreshing failed')
+			setTimeout(function (_) {
+				changeRskText('Refresh')
+			}, 3000)
+		}
+		else {
+			changeRskText('Refresh')
+		}
+	})
 }
 
 window.addEventListener('load', function (e) {